the comparison between as and cast
Possible Duplicate:
Direct casting vs 'as' operator?
Anyone can give a comparison between as and cast?
A straight cast will fail if the object being casted is not of the type requested. An as
-cast will instead return null. For example:
object obj = new object();
string str = (string)obj; // Throws ClassCastException
However:
object obj = new object();
string str = obj as string; // Sets str to null
When the object being casted is of the type you are casting to, the result is the same for either syntax: the object is successfully casted.
Note specifically that you should avoid the "as-and-invoke" pattern:
(something as SomeType).Foo();
Because if the cast fails, you will throw a NullReferenceException instead of a ClassCastException. This may cause you to chase down the reason that something
is null, when it's actually not! The uglier, but better code
((SomeType)something).Foo();
Will throw a ClassCastException when the object referenced by something
cannot be converted to SomeType
, and a NullReferenceException when something
is null.
"as" don't throw exception and return null if cast is failed.
It works similar this code:
if (objectForCasting is CastingType)
{
result = (CastingType)objectForCasting;
}
else
{
result = null;
}
The good practice is to use checking for null after using as statement:
CastingType resultVar = sourceVar as CastingType;
if (resultVar == null)
{
//Handle null result here...
}
else
{
// Do smth with resultVar...
}
Performing an explicit cast differs from using the as operator in three major aspects.
The as operator…
上一篇: (int)值或值为int?
下一篇: as和cast之间的比较