你不能只在 IL 中加载任何通用对象,因为没有办法将它存储在 IL 中(除了一些特殊类型,如string
)。您可以使用序列化(对于支持它的类型)来解决这个问题,但我认为这不是您想要的。此外,ldobj
服务于完全不同的目的。
但是您可以通过MethodInfo
与 C# 对运算符所做的非常相似的方式来执行此typeof
操作。这意味着:
- 使用
ldtoken
指令得到一个RuntimeMethodHandle
- 打电话
MethodBase.GetMethodFromHandle()
要一个MethodBase
- 将其投射到
MethodInfo
生成返回 的方法的整个代码MethodInfo
如下所示:
MethodInfo loadedMethod = …;
var getMethodMethod = typeof(MethodBase).GetMethod(
"GetMethodFromHandle", new[] { typeof(RuntimeMethodHandle) });
var createdMethod = new DynamicMethod(
"GetMethodInfo", typeof(MethodInfo), Type.EmptyTypes);
var il = createdMethod.GetILGenerator();
il.Emit(OpCodes.Ldtoken, loadedMethod);
il.Emit(OpCodes.Call, getMethodMethod);
il.Emit(OpCodes.Castclass, typeof(MethodInfo));
il.Emit(OpCodes.Ret);
var func = (Func<MethodInfo>)createdMethod.CreateDelegate(typeof(Func<MethodInfo>));
Console.WriteLine(func());