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

推荐订阅源

S
Secure Thoughts
S
Securelist
P
Proofpoint News Feed
D
DataBreaches.Net
Cisco Talos Blog
Cisco Talos Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
Project Zero
Project Zero
A
About on SuperTechFans
罗磊的独立博客
WordPress大学
WordPress大学
月光博客
月光博客
Latest news
Latest news
C
Cyber Attacks, Cyber Crime and Cyber Security
GbyAI
GbyAI
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
博客园 - 三生石上(FineUI控件)
F
Fortinet All Blogs
W
WeLiveSecurity
Attack and Defense Labs
Attack and Defense Labs
V
Visual Studio Blog
Blog — PlanetScale
Blog — PlanetScale
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
P
Privacy International News Feed
AI
AI
博客园 - 司徒正美
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Stack Overflow Blog
Stack Overflow Blog
M
MIT News - Artificial intelligence
Help Net Security
Help Net Security
T
Tor Project blog
V
Vulnerabilities – Threatpost
C
Cisco Blogs
I
Intezer
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
MyScale Blog
MyScale Blog
雷峰网
雷峰网
MongoDB | Blog
MongoDB | Blog
Forbes - Security
Forbes - Security
V
V2EX
Apple Machine Learning Research
Apple Machine Learning Research
T
Threat Research - Cisco Blogs
B
Blog RSS Feed
博客园 - 叶小钗
N
News and Events Feed by Topic
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Simon Willison's Weblog
Simon Willison's Weblog
C
CERT Recently Published Vulnerability Notes
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
N
News and Events Feed by Topic

博客园 - jierry

ASP.NET2.0控件一览---标准控件(2) ASP.NET2.0控件一览---标准控件(1) 控件开发时两种JS嵌入资源方式的使用 - jierry - 博客园 T-SQL tips(1)临时表和表变量 Flash Control for ASP.NET 2.0-Include Flash movies in your aspx pages 为DataGrid创建自定义列控件(四) 为DataGrid创建自定义列控件(三) - jierry - 博客园 为DataGrid创建自定义列控件(二) 为DataGrid创建自定义列控件(一) (转)SQLServer和Oracle的常用函数对比 《Effective C#》读书笔记(4) 《Effective C#》读书笔记(2) 《Effective C#》读书笔记(1) 选择合适的数据控件 自带图层的链接控件(DKLinks 1.0.0.323 ) 关于CodeBuild V3.0的一些想法 小工具:SQL存储过程解密修改工具 交叉表应用-成绩统计 现在提供第一版的存储过程生成器下载,欢迎大家试用
《Effective C#》读书笔记(3)
jierry · 2005-08-13 · via 博客园 - jierry

        Item 3: Prefer the is or as Operators to Casts

        第3项: 优先使用is/as进行类型转换        由于C#是强类型的语言,我们要尽量避免类型的转换。但是有时转换是无法避免的,这时我们要优先使用is/as来进行类型的转换,避免使用强制的类型转换。
       asis操作符并不能进行所有的用户定义的类型转换, 只有当runtime类型和目标类型一致时转换操作才会成功.它们永远不会为了满足程序调用请求而创建一个新的object,这样就使类型转换更加的安全。
        让我们先来看看is操作符。is操作符可以检查对象是否和指定的类型兼容,并返回判断结果。is操作符永远不会抛出异常。
       

Object o = new Object();
Boolean b1 
= (o is Object);  //b1为true
Boolean b2 = (o is Person);  //b2为false


        is操作符为我们检查类型的兼容性,而as操作符提供类型的转型方式,它可以简化代码的同时提高性能。

object o = Factory.GetObject( );

MyType t 

= o as MyType;if ( t != null )
{
  
// work with t, it's a MyType.
else
{
  
// report the failure.
}


        在上面的代码CLR会检查o所引用的对象是否和MyType兼容。如果兼容,as返回一个指向同一个对象的非空指针。如果不兼容,as返回null。但是要注意,as不能用于值类型的转换,否则返回null。