DynamicMethod를 사용하면 만든 대리인의 대상 인스턴스를 지정할 수 있습니다. 그러나 구조체 형식을 사용할 때이 작동하지 않는 것으로 나타납니다. 이 메서드에 바인딩 할 수 없다는 예외가있어 실패합니다. IL이 대상 인스턴스를 unbox하지 않기 때문에 오류가 있습니까?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()
);
참고 : 나는 유창 인터페이스의 Emitted
라이브러리를 사용하고 여기
Delegate.CreateDelegate
를 호출하지 않는 것이 좋습니다하시기 바랍니다) 일리노이. CodeGen Method의 코드는 다음과 같습니다.
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);
}
}