惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Threatpost
S
Securelist
D
Darknet – Hacking Tools, Hacker News & Cyber Security
T
Threat Research - Cisco Blogs
C
Cyber Attacks, Cyber Crime and Cyber Security
T
Tenable Blog
I
Intezer
G
GRAHAM CLULEY
Spread Privacy
Spread Privacy
T
Tor Project blog
V
Vulnerabilities – Threatpost
NISL@THU
NISL@THU
L
Lohrmann on Cybersecurity
Schneier on Security
Schneier on Security
MyScale Blog
MyScale Blog
The GitHub Blog
The GitHub Blog
S
Security @ Cisco Blogs
The Register - Security
The Register - Security
酷 壳 – CoolShell
酷 壳 – CoolShell
B
Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
L
LangChain Blog
人人都是产品经理
人人都是产品经理
T
Tailwind CSS Blog
MongoDB | Blog
MongoDB | Blog
小众软件
小众软件
The Hacker News
The Hacker News
Google DeepMind News
Google DeepMind News
Microsoft Security Blog
Microsoft Security Blog
U
Unit 42
博客园 - 叶小钗
Attack and Defense Labs
Attack and Defense Labs
Webroot Blog
Webroot Blog
大猫的无限游戏
大猫的无限游戏
Apple Machine Learning Research
Apple Machine Learning Research
H
Hackread – Cybersecurity News, Data Breaches, AI and More
aimingoo的专栏
aimingoo的专栏
T
Troy Hunt's Blog
V
Visual Studio Blog
P
Proofpoint News Feed
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
A
Arctic Wolf
T
The Exploit Database - CXSecurity.com
宝玉的分享
宝玉的分享
Vercel News
Vercel News
D
DataBreaches.Net
P
Palo Alto Networks Blog
AI
AI
Simon Willison's Weblog
Simon Willison's Weblog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC

博客园 - 啊不才

【转载备用】Linux内核编译 幸运的Windows 7 Party 社区活动 jQueryinAction学习笔记——01 - 啊不才 - 博客园 django的字符替换问题 如何在屏幕中央打开一个特定的窗口 KB937061和KB947738多次安装问题 BlogEngine.Net的皮肤 [How Do I]系列学习笔记——001:学习一些技巧 继承类中override和new的区别 我提交的ACM题库的答案 调用Master页面上的属性 NotePad++很好用,但是我真的不想再用它了 BlogEngine的SQL Server数据库配置 关于asp:ScriptManager与Script代码块的位置关系问题 NHiBernate学习笔记(1) 使用JMail.NET时遇到的问题 ToString()方法与Convert.ToString()的差异 『框架设计(第2版)CLR Via C#』学习笔记——常量 【已解决,看后文】使用BlogEngine.net的扩展插件Silverlight Player Extension遇到的问题
『框架设计(第2版)CLR Via C#』学习笔记——使用is和as操作符来进行强制类型转换
啊不才 · 2008-07-03 · via 博客园 - 啊不才

is操作符是检查一个对象是不是兼容于指定的类型,并返回一个Boolean值:true或false。因此is操作符永远不会抛出异常。
例如如下代码:

1Object o = new Object();
2Boolean b1 = (o is Object); //b1 is true
3Boolean b2 = (o is Student); //b2 is false

如果对象是null引用,则总是返回false。

那么as是用来干吗的哪?还是让我们先来看一段代码吧:

1if (o is Student)
2{
3    Student s = (Student)o;
4    // do rest things
5}

在上段代码中,CLR实际上会检查两次对象的类型。第一次是is操作符核实o是否兼容于Student类型。如果答案是肯定的,那么进入if内部,执行第一句就出现类型转化,这时CLR再次核实o是否引用了一个Student。
这里CLR的类型检查增强了安全性,但是同时也无疑会对性能造成一定的影响,因为CLR首先必须判断变量o引用的对象是实际的对象,然后CLR必须遍历继承层次结构,用每个基类型去核对指定的类型Student。
正是因为这是一个非常常用的功能,所以C#专门的提供了一个as操作符,目的就是为了简化这种代码的编写,同时提升性能。

1Student s = o as Student;
2if (s != null)
3{
4    // do rest things
5}

这里就只检查了一次,CLR核实o是否兼容于Student类型,如果是,则返回对同一个对象的一个非null的引用。如果不兼容于Student类型,as操作符就会返回null。这里需要说明一下if语句只是检查s是否为null,这个过程相较于校验对象的类型,这个检查能更快的执行。