【发布时间】:2011-07-13 12:33:35
【问题描述】:
在以下代码中,发生了装箱(在 Generic
using System;
namespace Test
{
static class Program
{
static void Main()
{
Generic<string> generic = new Generic<string>("test");
generic.Print();
}
}
class Generic<Type>
{
Type value;
public Generic(Type value)
{
this.value = value;
}
public void Print()
{
Console.WriteLine(value);
}
}
}
ILSpy 输出:
.method public hidebysig
instance void Print () cil managed
{
// Method begins at RVA 0x207d
// Code size 17 (0x11)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldfld !0 class Test.Generic`1<!Type>::'value'
IL_0006: box !Type
IL_000b: call void [mscorlib]System.Console::WriteLine(object)
IL_0010: ret
} // end of method Generic`1::Print
这是装箱和调用 Console.WriteLine(object)。我假设它会简单地调用 Console.WriteLine(string)。这是怎么回事?
【问题讨论】:
-
看起来它使用了一些代码重用。
-
仅供参考,调用泛型参数
Type是不好的做法,因为它可能与System.Type冲突。