问题
Possible Duplicate:
Casting vs using the ‘as’ keyword in the CLR
I know there are a lot of questions about casts but I don't know the specific names of these two casts so I'm not sure where to look. What are the differences between the two casts below?
TreeNode treeNode = (TreeNode)sender; // first cast
TreeNode treeNode = (sender as TreeNode); //second cast
回答1:
The first type of cast is called an "explicit cast" and the second cast is actually a conversion using the as
operator, which is slightly different than a cast.
The explicit cast (type)objectInstance
will throw an InvalidCastException
if the object is not of the specified type.
// throws an exception if myObject is not of type MyTypeObject.
MyTypedObject mto = (MyTypedObject)myObject;
The as
operator will not throw an exception if the object is not of the specified type. It will simply return null
. If the object is of the specified type then the as
operator will return a reference to the converted type. The typical pattern for using the as
operator is:
// no exception thrown if myObject is not MyTypedObject
MyTypedObject mto = myObject as MyTypedObject;
if (mto != null)
{
// myObject was of type MyTypedObject, mto is a reference to the converted myObject
}
else
{
// myObject was of not type MyTypedObject, mto is null
}
Take a look at the following MSDN references for more details about explicit casting and type conversion:
- Casting (C#)
- Casting and Type Conversions
- How to: Safely Cast by Using as and is Operators
回答2:
If sender
is not a TreeNode
than the first one throws exception and second one returns null
.
来源:https://stackoverflow.com/questions/13805617/difference-between-type-cast-and-as-cast