[英]Boxing and Unboxing
I have a small doubt regarding Boxing and Unboxing in C#. 我对C#中的拳击和拆箱有一点疑问。
int i=1;
System.Int32 j = i;
above code can be called as boxing? 上面的代码可以称为拳击?
No, that's not boxing at all. 不,那根本不是拳击。
int
is just an alias for System.Int32
. int
只是 System.Int32
的别名。 That code is equivalent to: 该代码相当于:
int i = 1;
int j = i;
For boxing to occur, there has to be a conversion to a reference type, eg 要进行装箱,必须转换为参考类型,例如
int i = 1;
object j = i;
Or: 要么:
int i = 1;
IComparable j = i;
Just to extend Jon's answer just a little bit, boxing will also occur, when you call non-overridden or non-virtual methods of the base class also, like 只是稍微扩展Jon的答案,当你调用基类的非重写或非虚方法时,也会发生装箱,就像
i.GetType(); //boxing occur here
or pass int
to a method, which requires a reference type 或者将
int
传递给需要引用类型的方法
void Foo(object obj) {}
Foo(i); //boxing, no overload takes an int
In the first example IL
you can clearly see box
instruction 在第一个示例
IL
您可以清楚地看到box
指令
int i = 5;
i.GetType();
IL_0000: ldc.i4.5
IL_0001: stloc.0 // i
IL_0002: ldloc.0 // i
IL_0003: box System.Int32 //<---- boxing
IL_0008: call System.Object.GetType
If you don't override virtual methods in your value types, they will also be boxed when calling them 如果不覆盖值类型中的虚方法,则在调用它们时也会将它们装箱
enum MyEnum {}
var e = new MyEnum();
e.ToString(); //box will occur here, see IL for details
IL_0000: ldc.i4.0
IL_0001: stloc.0 // e
IL_0002: ldloc.0 // e
IL_0003: box UserQuery.MyEnum
IL_0008: callvirt System.Object.ToString
The same situations with structs, except they will use callvirt
opcode, that will box the struct if nessecary, 与结构相同的情况,除了它们将使用
callvirt
操作码,如果nessecary将包装结构,
No. int is a value type. 不,int是值类型。
Boxing occurs when you assign a value type to an Object. 将值类型分配给Object时会发生Boxing。
It is not boxing . 这不是拳击 。
int
is an alias for System.Int32
. int
是System.Int32
的别名。 So your code is equavalent to; 所以你的代码相当于;
int i = 1;
int j = i;
For boxing, there should be a conversion to an object or an interface. 对于装箱,应该转换为对象或接口。 Like;
喜欢;
int i = 1;
object j = i;
A value of a class type can be converted to type object or to an interface type that is implemented by the class simply by treating the reference as another type at compile-time.
可以将类类型的值转换为类型对象或由类实现的接口类型,只需在编译时将引用视为另一种类型即可。 Likewise, a value of type object or a value of an interface type can be converted back to a class type without changing the reference (but of course a run-time type check is required in this case).
同样,类型对象的值或接口类型的值可以在不更改引用的情况下转换回类类型(但在这种情况下,当然需要运行时类型检查)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.