Casting: (NewType) vs. Object as NewType
Possible Duplicate:
Casting vs using the 'as' keyword in the CLR
What is actually the difference between these two casts?
SomeClass sc = (SomeClass)SomeObject;
SomeClass sc2 = SomeObject as SomeClass;
Normally, they should both be explicit casts to the specified type?
The former will throw an exception if the source type can't be cast to the target type. The latter will result in sc2 being a null reference, but no exception.
[Edit]
My original answer is certainly the most pronounced difference, but as Eric Lippert points out, it's not the only one. Other differences include:
And finally, using 'as' vs. the cast operator, you're also saying "I'm not sure if this will succeed."
Also note that you can only use the as keyword with a reference type or a nullable type
ie:
double d = 5.34;
int i = d as int;
will not compile
double d = 5.34;
int i = (int)d;
will compile.
Typecasting using "as" is of course much faster when the cast fails, as it avoids the expense of throwing an exception.
But it is not faster when the cast succeeds. The graph at http://www.codeproject.com/KB/cs/csharpcasts.aspx is misleading because it doesn't explain what it's measuring.
The bottom line is:
If you expect the cast to succeed (ie a failure would be exceptional), use a cast.
If you don't know if it will succeed, use the "as" operator and test the result for null.
上一篇: 'ref'和'out'关键字有什么区别?