在下面的代码,拳击发生(在通用<类型> .PRINT):奇怪的通用行为
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(对象) 。我认为它只会调用Console.WriteLine(string)。这里发生了什么?
看起来像使用一些代码重用。 –
Fyi,调用泛型参数'Type'是不好的做法,因为它可能与'System.Type'冲突。 –