Difference between type cast and 'as' cast [duplicate]

两盒软妹~` 提交于 2019-12-12 19:19:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!