可能重复:
Direct casting vs 'as' operator?
Casting vs. using the as keyword in the CLRC#:有没有为Type(类型)的东西之间的差值Vs东西
在C#中,什么差别
var obj = (Array)Something
vs
var obj = Something as Array
可能重复:
Direct casting vs 'as' operator?
Casting vs. using the as keyword in the CLRC#:有没有为Type(类型)的东西之间的差值Vs东西
在C#中,什么差别
var obj = (Array)Something
vs
var obj = Something as Array
var obj = (Array)Something
将抛出InvalidCastExcpetion如果Something
不是从System.Array
衍生或不具有System.Array
一个conversion operator。这可以与值类型和引用类型一起使用。
var obj = Something as Array
将返回null
(obj
会null
)如果Something
不是从System.Array
衍生或不具有System.Array
一个conversion operator。这只能用于引用类型。你需要box你值类型第一。
以及Danijels答案
第一个可以用于任何类型。
as
运算符只能用于引用类型。
这是许多[问题](http://stackoverflow.com/questions/496096/casting-vs-using-the-as-keyword-in-the-clr)在这里。这些天没有人阅读过文档吗? – 2010-10-05 08:29:55
在搜索此网站时遇到'[c#] typecast'显示此问题:http://stackoverflow.com/questions/3724051/what-is-difference-between-normal-typecasting-and-using-as-keyword-closed而其他问题又被关闭了。投票结束 – 2010-10-05 08:33:27