int i = 5;
string str = i.ToString();
String str1=(String) i.ToString();
因为 Int
是值类型而 String
是引用类型
所以是装箱还是拆箱???
编辑: 现在第二个声明是装箱还是拆箱???
最佳答案
您的代码不是拆箱或装箱的示例,而是 Int32.ToString()
的方法调用并将返回值分配给 string
。 i.ToString()
调用不会将 int
分配给对象,而是将其传递给返回 string
的方法。带有 (string)
转换的第二行是多余的,C# 编译器甚至不会将它发送到 IL 中。
例如,如果你在 main 方法中有这个:
.method private hidebysig static
void Main (
string[] args
) cil managed
{
// Method begins at RVA 0x2050
// Code size 19 (0x13)
.maxstack 1
.entrypoint
.locals init (
[0] int32 i
)
IL_0000: ldc.i4.5
IL_0001: stloc.0
IL_0002: ldloca.s i
IL_0004: call instance string [mscorlib]System.Int32::ToString()
IL_0009: pop
IL_000a: ldloca.s i
IL_000c: call instance string [mscorlib]System.Int32::ToString() // cast isn't here
IL_0011: pop
IL_0012: ret
} // end of method Program::Main
如果您要装箱一个整数:
int i = 1;
object iBox = i;
发出:
.locals init (
[0] int32 i,
[1] object o
)
IL_0000: nop
IL_0001: ldc.i4.5
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: box [mscorlib]System.Int32
IL_0009: stloc.1
IL_000a: ret
注意 box
操作代码。如果您不确定某些东西是装箱还是拆箱,您可以查看 IL 并查看此操作代码是否存在。
如果您要拆箱一个整数:
int j = (int) iBox;
其他值类型的过程类似,例如 bool
或 double
。
关于c# - 是装箱还是拆箱?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22163664/