DynamicMethods 允许您为您创建的委托指定目标实例。但是,当您使用结构类型时,这似乎不起作用。它失败并出现异常,告诉我它无法绑定到此方法。错误是因为我的 IL 没有拆箱目标实例吗?
如果我在这里将 A 更改为一个类,它可以正常工作。我究竟做错了什么?(另外请不要建议调用Delegate.CreateDelegate
绑定到带有目标实例的GetType方法)
这是一个示例复制:
struct A { }
... //then some where in code::
Func<Type> f = CodeGen.CreateDelegate<Func<Type>>(il=>
il.ldarga_s(0)
.constrained(typeof(A))
.callvirt(typeof(object).GetMethod("GetType"))
.ret(),
name:"Constrained",
target:new A()
);
注意:我正在Emitted
为 IL 的流利界面使用该库。此外,这里是 CodeGen 方法的代码。
public static class CodeGen
{
public static TDelegate CreateDelegate<TDelegate>(Action<ILGenerator> genFunc, string name = "", object target = null, bool restrictedSkipVisibility = false)
where TDelegate:class
{
ArgumentValidator.AssertGenericIsDelegateType(() => typeof(TDelegate));
ArgumentValidator.AssertIsNotNull(() => genFunc);
var invokeMethod = typeof(TDelegate).GetMethod("Invoke");
var @params = invokeMethod.GetParameters();
var paramTypes = new Type[@params.Length + 1];
paramTypes[0] = target == null ? typeof(object) : target.GetType();
@params.ConvertAll(p => p.ParameterType)
.CopyTo(paramTypes, 1);
var method = new DynamicMethod(name ?? string.Empty, invokeMethod.ReturnType, paramTypes, restrictedSkipVisibility);
genFunc(method.GetILGenerator());
return method.CreateDelegate<TDelegate>(target);
}
}