看来他们俩在概念上是不同的 .
Direct Casting
类型不必严格相关 . 它有各种口味 .
Custom implicit/explicit casting: 通常会创建一个新对象 .
Value Type Implicit: 复制而不会丢失信息 .
Value Type Explicit: 复制和信息可能会丢失 .
IS-A relationship: 更改引用类型,否则抛出异常 .
Same type: 'Casting is redundant' .
感觉对象将被转换为其他东西 .
AS operator
类型有直接关系 . 如:
参考类型: IS-A relationship 对象始终相同,只是参考更改 .
值类型: Copy 装箱和可空类型 .
感觉就像你要以不同的方式处理对象 .
Samples and IL
class TypeA
{
public int value;
}
class TypeB
{
public int number;
public static explicit operator TypeB(TypeA v)
{
return new TypeB() { number = v.value };
}
}
class TypeC : TypeB { }
interface IFoo { }
class TypeD : TypeA, IFoo { }
void Run()
{
TypeA customTypeA = new TypeD() { value = 10 };
long longValue = long.MaxValue;
int intValue = int.MaxValue;
// Casting
TypeB typeB = (TypeB)customTypeA; // custom explicit casting -- IL: call class ConsoleApp1.Program/TypeB ConsoleApp1.Program/TypeB::op_Explicit(class ConsoleApp1.Program/TypeA)
IFoo foo = (IFoo)customTypeA; // is-a reference -- IL: castclass ConsoleApp1.Program/IFoo
int loseValue = (int)longValue; // explicit -- IL: conv.i4
long dontLose = intValue; // implict -- IL: conv.i8
// AS
int? wraps = intValue as int?; // nullable wrapper -- IL: call instance void valuetype [System.Runtime]System.Nullable`1::.ctor(!0)
object o1 = intValue as object; // box -- IL: box [System.Runtime]System.Int32
TypeD d1 = customTypeA as TypeD; // reference conversion -- IL: isinst ConsoleApp1.Program/TypeD
IFoo f1 = customTypeA as IFoo; // reference conversion -- IL: isinst ConsoleApp1.Program/IFoo
//TypeC d = customTypeA as TypeC; // wouldn't compile
}