What is difference between normal typecasting and using “AS” keyword
Possible Duplicates:
Direct casting vs 'as' operator?
Casting: (NewType) vs. Object as NewType
What is difference between normal typecasting and using “AS” keyword?
如果对象是错误的类型,使用as
将会优雅地失败,并且结果值将为null,而普通的强制类型会抛出InvalidCastException:
object x = new object();
string y = x as string; // y == null
string z = (string)x; // InvalidCastException
The use cases of the two operators are superficially similar, but semantically quite different. A cast communicates to the reader "I am certain that this conversion is legal and I am willing to take a runtime exception if I'm wrong". The "as" operator communicates "I don't know if this conversion is legal or not; we're going to give it a try and see how it goes".
For more on this topic see my article on the subject:
http://blogs.msdn.com/b/ericlippert/archive/2009/10/08/what-s-the-difference-between-as-and-cast-operators.aspx
as
铸造会在需要时抛出异常,而通常的铸造可以。
Object a = new Object();
String b = a as String;
if(b != null) // always false for this example.
{}
链接地址: http://www.djcxy.com/p/73728.html
上一篇: C#中用于类型转型的最佳实践是哪种?