c# - 是装箱还是拆箱?

标签 c# boxing unboxing

int i = 5;

string str = i.ToString();

String str1=(String) i.ToString();

因为 Int 是值类型而 String 是引用类型

所以是装箱还是拆箱???

编辑: 现在第二个声明是装箱还是拆箱???

最佳答案

您的代码不是拆箱或装箱的示例,而是 Int32.ToString() 的方法调用并将返回值分配给 stringi.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;

其他值类型的过程类似,例如 booldouble

关于c# - 是装箱还是拆箱?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22163664/

相关文章:

c# - 为什么未装箱的类型有方法?

c# - 将对象类型数据转换为值类型的最佳方法

java - 为什么不在此 Java 代码中应用拆箱?

java - 整数自动拆箱和自动装箱会带来性能问题吗?

c# - 从 c++ dll 中的线程回调更新 WPF 图像源

c# - 在 IronPython 和 IronRuby 中打包脚本源文件

java - 内部编译器错误 ArrayIndexOutOfBoundsException : -1 . ..generateUnboxingConversion

c# - 一次只触发一个自定义验证器

c# - 将元组列表转换为字符串的更好方法

c# - 无法将 List<char> 作为参数传递给 List<object>?