这个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
{
}
{
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类型的转换