查看泛型的IL
我们在开发中经常用到泛型,下面一起通过IL来查看泛型背后做了那些工作
示例代码
示例代码如下:
using System;
namespace MyCollection
{
public class GenericExample
{
public static T GetT<T>(T value)
{
return value;
}
public static void Main(string[] args)
{
int a = GetT(3);
string str = GetT("I'am String");
Console.WriteLine("value1:{0}\t Value2:{1}",a,str);
}
}
}
IL查看
通过这可以看到泛型在解释时,也会生成一个新的Class GetT(!!T):!!T
IL代码如下
.method public hidebysig static
void Main (
string[] args
) cil managed
{
// Method begins at RVA 0x218c
// Code size 38 (0x26)
.maxstack 3
.entrypoint
.locals init (
[0] int32 a,
[1] string str
)
IL_0000: nop
IL_0001: ldc.i4.3
//这里的T转成了int32
IL_0002: call !!0 MyCollection.GenericExample::GetT<int32>(!!0)
IL_0007: stloc.0
IL_0008: ldstr "I'am String"
//而在这儿T的类型又转成了string
IL_000d: call !!0 MyCollection.GenericExample::GetT<string>(!!0)
IL_0012: stloc.1
IL_0013: ldstr "value1:{0}\t Value2:{1}"
IL_0018: ldloc.0
IL_0019: box [mscorlib]System.Int32
IL_001e: ldloc.1
IL_001f: call void [mscorlib]System.Console::WriteLine(string, object, object)
IL_0024: nop
IL_0025: ret
} // end of method GenericExample::Main