DynamicMethods允許您爲您創建的委託指定目標實例。但是,看起來這在您使用結構類型時不起作用。它會失敗並告訴我它不能綁定到這個方法。是因爲我的IL沒有解開目標實例的錯誤?爲什麼我不能將DynamicMethod綁定到結構實例?
如果我在這裏改變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);
}
}