Grisson's .net

源码之前,了无秘密

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

这个Item鼓励大家多是用is/as,除非的在不得已的情况下才是用原始的强制的类型转换

值得注意的地方:
as / is:作类型转换时,是检查其转换对象的runtime-type,它不会执行任何用户自定的操作。在转换时其runtime-type必须与目标类型相同,或是其继承自目标类型。

as:不能用于value type,因为任何value type不能为null,而当as失败时返回null

cast:做类型转换时,是检查去转换对象的compile time-type,他执行用户自定的转换操作。

public class SecondType
{
  
private MyType _value;

  
public static implicit operator MyType(SecondType t)
  
{
    
return t._value;
  }

}


//version 1
object o = Factory.GetObject() //返回SecondType
MyType t= o as MyType;
if(null != t)
{
  Console.WriteLine(
"is Null");
}

else
{
  Console.WriteLine(
"is Not Null");

}


//version 2
try
{
  MyType t1;
  t1 
= (MyType)o;
  
if(null != t1)
  
{
  }

  
else
  
{
  }

}

catch
{
}

很可惜的告诉你两个转换都失败。
我认为原因是:
version 1:虽然o的runtime-type是SecondType,但很可惜as不会执行用户自定义操作
version 2:虽然cast会执行用户自定义的操作,但是o的compile time-type是object,他没有定义到MyType类型的转换
posted on 2005-08-12 23:12  海盗  阅读(306)  评论(0编辑  收藏  举报