C#发出对泛型方法的调用
上课C#发出对泛型方法的调用,c#,generics,cil,reflection.emit,C#,Generics,Cil,Reflection.emit,上课 class C { public T Get<T>() { return default; } public void M() { int i = this.Get<Int32>(); } } 产生 ldarg.0 call instance !!0 C::Get<M0>(string) // ^^ ret ldarg.0 呼
class C
{
public T Get<T>()
{
return default;
}
public void M()
{
int i = this.Get<Int32>();
}
}
产生
ldarg.0
call instance !!0 C::Get<M0>(string)
// ^^
ret
ldarg.0
呼叫实例!!0 C::Get(字符串)
// ^^
ret
但我需要得到
ldarg.0
call instance !!0 C::Get<int32>(string)
// ^^^^^
ret
ldarg.0
呼叫实例!!0 C::Get(字符串)
// ^^^^^
ret
(注意调用C.Get
中的不同类型参数)
在发出对泛型CfFunction的调用时,如何传递泛型参数的类型(即,去掉
M0
,让它改为int32
)您需要将类型参数替换为:
ldarg.0
call instance !!0 C::Get<int32>(string)
// ^^^^^
ret
ilGenerator.Emit(OpCodes.Ldarg_0);
ilGenerator.Emit
(
OpCodes.Call,
typeof(C)
.GetMethod(nameof(C.Get), BindingFlags.Instance)
.MakeGenericMethod(typeof(int))
);