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

推荐订阅源

Google Online Security Blog
Google Online Security Blog
博客园_首页
酷 壳 – CoolShell
酷 壳 – CoolShell
Jina AI
Jina AI
博客园 - Franky
大猫的无限游戏
大猫的无限游戏
Hugging Face - Blog
Hugging Face - Blog
博客园 - 司徒正美
V
V2EX
雷峰网
雷峰网
云风的 BLOG
云风的 BLOG
V
Visual Studio Blog
F
Full Disclosure
Y
Y Combinator Blog
V
V2EX - 技术
Attack and Defense Labs
Attack and Defense Labs
S
Security @ Cisco Blogs
Schneier on Security
Schneier on Security
Microsoft Azure Blog
Microsoft Azure Blog
SecWiki News
SecWiki News
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
The GitHub Blog
The GitHub Blog
量子位
PCI Perspectives
PCI Perspectives
S
Secure Thoughts
D
Darknet – Hacking Tools, Hacker News & Cyber Security
AWS News Blog
AWS News Blog
Blog — PlanetScale
Blog — PlanetScale
爱范儿
爱范儿
K
Kaspersky official blog
B
Blog
A
Arctic Wolf
Hacker News: Ask HN
Hacker News: Ask HN
L
LangChain Blog
T
Tor Project blog
P
Privacy & Cybersecurity Law Blog
Recent Announcements
Recent Announcements
宝玉的分享
宝玉的分享
The Register - Security
The Register - Security
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
L
Lohrmann on Cybersecurity
D
Docker
A
About on SuperTechFans
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Google DeepMind News
Google DeepMind News
The Last Watchdog
The Last Watchdog
S
Security Affairs
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
P
Privacy International News Feed
Simon Willison's Weblog
Simon Willison's Weblog

博客园 - 风前絮~~

回来啦 Rainbow分页解决方案 FTB2.0和CuteEditor的一些问题 testFTB2.0 testCuteEditor 看看MS内部对.NET的使用情况... base想到... 多个Main函数的应用程序 - 风前絮~~ - 博客园 伟大架构师的秘密 权限管理越来越复杂 ASP.NET跨应用程序进行登录的解决 Server的Transfer和Response的Redirect FreeTextBox实现机制 FreeTextBox的ToolbarButton整理 Testing vs Debugger 稍不留神产生代码垃圾 再比较动态调用代码 .NET建议使用的大小写命名原则 using的几种用法
C#中"is" vs "as" - 风前絮~~
风前絮~~ · 2004-09-16 · via 博客园 - 风前絮~~

        在数据类型转换中,C#相对其它语言来说是比较严格的,要求显式进行数据转化。
        为了操作方便,C#也提供了一种is操作符进行转换,十分方便,它自动检查时局是否和类型兼容,并返回结果。而且它不会抛出异常。如果对象引用为null,则is总返回false。

            if (cls1 is Class2) 
            
{
                Class2 cls2 
= (Class2)cls1;
            }

            
else
                System.Console.WriteLine(
"Error 2!");

      平时自己也多用这种方式来做类型转化的,但今天看了个文章,对比了另外一种方式,as操作符进行转换,才知道as比is可以稍微地提高性能的。

            Class2 cls2 = cls1 as Class2;
            
if (cls2!=null)
               System.Console.WriteLine(
"Ok");
            
else
               System.Console.WriteLine(
"Error!");

        as稍微不同,它检查引用对象是否兼容,如果不兼容则返回null,因此需要做null的判断。


        对比两种方式,is需要做两次对象的类型检查,而as需要做一次对象类型检查,再加一次null的检查,而null检查开销比对象类型检查少。相对as的方法效率高些。

        看来日常写的一些习惯性的代码总可以找到改进的地方的,将新的方式再作为习惯不是更好?