c# - valueType.ToString() 是否对 valueType 进行强制转换?

标签 c# value-type boxing unboxing

比方说,我在 c# 中有以下代码

int x = 0;
x.ToString();

这是否在内部对 x 进行装箱? 有没有办法从 visual studio 中看到这种情况?

最佳答案

在此特定情况下,您使用的是 System.Int32(int)。该类型重新定义了 ToStringEqualsGetHashCode,因此没有装箱。

如果您使用不重新定义 ToStringstruct,您将拥有一个 constrained callvirtSystem.对象.ToString()constrained的定义:

When a callvirt method instruction has been prefixed by constrained thisType, the instruction is executed as follows:

  • If thisType is a value type and thisType implements method then ptr is passed unmodified as the 'this' pointer to a call method instruction, for the implementation of method by thisType.
  • If thisType is a value type and thisType does not implement method then ptr is dereferenced, boxed, and passed as the 'this' pointer to the callvirt method instruction.

因此,如果值类型实现了 ToString,则没有装箱,如果没有实现,则有装箱……有趣。我不知道。

对于 System.Object 中定义的非虚拟方法,如 GetType(),值类型始终被装箱。刚刚测试过:

5.GetType();

生成的 IL 代码:

IL_0001: ldc.i4.5
IL_0002: box [mscorlib]System.Int32
IL_0007: call instance class [mscorlib]System.Type [mscorlib]System.Object::GetType()

关于c# - valueType.ToString() 是否对 valueType 进行强制转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18615648/

相关文章:

c# - 在 C# 中从列表到对象的装箱和拆箱

c# - .net - 锁定盒装值而不是新对象

c# - 检查 null 时,泛型函数是否将值类型隐式转换为对象?

java - 澄清拳击

java - 我怎样才能自动装箱这个类?

c# - 可以使用传统的 File.CreateText(path) 代替 IsolatedStorageFile 吗?

c# - 我们可以在单个 asp.net 应用程序中拥有来自 2 个不同数据库的 2 个不同的 Oracle 依赖项吗

c# - 在不知道盒子里面是什么的情况下拆箱 uint/int

c# - 让网络中的客户端找到彼此

c# - 在 asp.net 回发期间禁用和启用按钮