DynamicMethodでは、作成するデリゲートのターゲットインスタンスを指定できます。しかし、struct型を使用すると、これは機能しません。このメソッドにバインドできないという例外が発生して失敗します。私のイリノイは目標のインスタンスをアンボックスしないのでエラーですか?DynamicMethodをstructインスタンスにバインドできないのはなぜですか?
ここでAをクラスに変更すると、問題なく動作します。私は間違って何をしていますか?
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()
);
注: (また、ターゲット・インスタンスにGetTypeメソッドにバインドするDelegate.CreateDelegate
を呼び出すことをお勧めしないでください)
ここでは、サンプルREPROである私は、流れるようなインターフェイスのため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);
}
}