2

可能重复:
强制转换与在 CLR 中使用“as”关键字

我知道有很多关于演员表的问题,但我不知道这两个演员表的具体名称,所以我不知道去哪里找。下面这两个演员有什么区别?

TreeNode treeNode = (TreeNode)sender; // first cast
TreeNode treeNode = (sender as TreeNode); //second cast
4

2 回答 2

12

第一种类型的强制转换称为“显式强制转换”,第二种强制转换实际上是使用as运算符进行的转换,这与强制转换略有不同。

如果对象不是指定的类型,显式转换(type)objectInstance将抛出一个。InvalidCastException

// throws an exception if myObject is not of type MyTypeObject.
MyTypedObject mto = (MyTypedObject)myObject;

如果对象不是指定类型,as则运算符不会抛出异常。它会简单地返回null。如果对象属于指定类型,则as运算符将返回对转换后类型的引用。使用as运算符的典型模式是:

// 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
}

有关显式转换和类型转换的更多详细信息,请查看以下 MSDN 参考:

于 2012-12-10T17:11:27.773 回答
7

If senderis not a TreeNodethan 第一个抛出异常,第二个返回null

于 2012-12-10T17:07:20.257 回答