类型转换和'as'转换之间的区别 [英] Difference between type cast and 'as' cast

查看:174
本文介绍了类型转换和'as'转换之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

投放vs使用CLR中的'as'关键字


我知道有很多关于演员的问题,但我不知道这两个演员的具体名称,所以我不知道在哪里看。

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


解决方案

一个显式转换,第二个转换实际上是使用作为运算符的转换,这与转换稍有不同。


$ b b

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

  //如果myObject不是MyTypeObject类型,则抛出异常。 
MyTypedObject mto =(MyTypedObject)myObject;
作为运算符不会引发异常如果对象不是指定的类型。它将简单地返回 null 。如果对象是指定类型,则 as 运算符将返回对转换类型的引用。使用作为运算符的典型模式是:

  //无异常抛出,如果myObject不是MyTypedObject 
MyTypedObject mto = myObject as MyTypedObject;
if(mto!= null)
{
// myObject的类型为MyTypedObject,mto是对转换的myObject的引用
}
else
{
// myObject的类型不是MyTypedObject,mto为null
}

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




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

解决方案

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:

这篇关于类型转换和'as'转换之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆