gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:10:52 27 4
gpt4 key购买 nike

比方说,我在 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com