java赋值运算as_直接投射vs 'as'运算符?

看来他们俩在概念上是不同的 .

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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值