gpt4 book ai didi

c# - 当作为具有接口(interface)约束的通用参数传递时,值类型是否被装箱?

转载 作者:太空狗 更新时间:2023-10-29 21:27:34 26 4
gpt4 key购买 nike

(作为回答这个问题的研究结果,我(认为我有!)确定答案是否定的。但是,我不得不在几个不同的地方寻找答案,所以我认为这个问题仍然有值(value)。但如果社区投票决定关闭,我不会感到沮丧。)

例如:

void f<T>(T val) where T : IComparable
{
val.CompareTo(null);
}

void g()
{
f(4);
}

4 是装箱的吗?我知道将值类型显式转换为它实现的接口(interface)会触发装箱:

((IComparable)4).CompareTo(null); // The Int32 "4" is boxed

我不知道的是,将值类型作为具有接口(interface)约束的泛型参数传递是否等同于执行强制转换——“其中 T 是一个 IComparable”的语言有点建议强制转换,但只是转 TIComparable 似乎会破坏通用的整个目的!

为了澄清,我想确保上面的代码中没有发生这些事情:

  1. g 调用 f(4) 时,4 被转换为 IComparable,因为有一个 IComparable 约束 f 的参数类型。
  2. 假设 (1) 没有发生,在 f 中,val.CompareTo(null) 不会从 Int32 中转换 val IComparable 以调用 CompareTo

但我想了解一般情况;不仅仅是 intIComparable 会发生什么。

现在,如果我将以下代码放入 LinqPad:

void Main()
{
((IComparable)4).CompareTo(null);
f(4);
}

void f<T>(T val) where T : IComparable
{
val.CompareTo(null);
}

然后检查生成的 IL:

IL_0001:  ldc.i4.4    
IL_0002: box System.Int32
IL_0007: ldnull
IL_0008: callvirt System.IComparable.CompareTo
IL_000D: pop
IL_000E: ldarg.0
IL_000F: ldc.i4.4
IL_0010: call UserQuery.f

f:
IL_0000: nop
IL_0001: ldarga.s 01
IL_0003: ldnull
IL_0004: constrained. 01 00 00 1B
IL_000A: callvirt System.IComparable.CompareTo
IL_000F: pop
IL_0010: ret

很明显,对于显式转换,装箱按预期发生,但在 f 本身* 或其在 Main< 中的调用位置,没有明显的装箱。这是个好消息。但是,这也只是一种类型的一个例子。这种没有装箱的情况是否可以假设为适用于所有情况?


* This MSDN article讨论了 constrained 前缀并指出只要被调用的方法是在类型本身上实现的(相对于一个基类)。我不确定的是,当我们到达此处时,该类型是否始终是值类型。

最佳答案

正如您已经知道的,当一个结构被传递给泛型方法时,它不会被装箱。

运行时为每个“类型参数”创建新方法。当您使用值类型调用泛型方法时,您实际上是在调用为​​相应值类型创建的专用方法。所以不需要装箱。

当调用未在您的结构类型中直接实现的接口(interface)方法时,将发生装箱。规范在这里调用它:

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.

This last case can occur only when method was defined on Object, ValueType, or Enum and not overridden by thisType. In this case, the boxing causes a copy of the original object to be made. However, because none of the methods of Object, ValueType, and Enum modify the state of the object, this fact cannot be detected.

因此,只要您显式[1] 在结构本身中实现接口(interface)成员,就不会发生装箱。

How, when and where are generic methods made concrete?

1.不要与显式接口(interface)实现相混淆。也就是说,你的接口(interface)方法应该在struct本身而不是它的基类型中实现。

关于c# - 当作为具有接口(interface)约束的通用参数传递时,值类型是否被装箱?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25508615/

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