我只是好奇如何使用Emit
.
我生成了这个类
public class AClass : IDynamicProxyTestInterface
{
private DynamicProxy<IDynamicProxyTestInterface> proxy;
public AClass(DynamicProxy<IDynamicProxyTestInterface> p)
{
proxy = p;
}
public void Hello()
{
// Here I want to do the following
Int32 code = 123456;
proxy.HandleCall(code);
}
}
评论部分是我一直在努力弄清楚的。
我有这个代码(注释掉的东西是我一直在打开和关闭的东西,试图让它工作)
var methodBuilder = typeBuilder.DefineMethod(
methodInfo.Name,
MethodAttributes.Public | MethodAttributes.Virtual,
methodInfo.ReturnType,
methodInfo.GetParameters().Select(p => p.GetType()).ToArray()
);
var methodIlGen = methodBuilder.GetILGenerator();
// Add proxy call to method
var emptyAction = new DynamicProxyOnBuilder();
ProxyCalls.Add(methodInfo.GetHashCode(), emptyAction);
// Drop method info hash into local variable 0
//var hash = methodInfo.GetHashCode();
//methodIlGen.Emit(OpCodes.Ldc_I4, hash);
//methodIlGen.DeclareLocal(typeof(Int32), false);
//methodIlGen.Emit(OpCodes.Stloc_0);
// Create local variable for instance of this DynamicProxy
methodIlGen.Emit(OpCodes.Ldarg_0);
methodIlGen.Emit(OpCodes.Ldflda, proxyField);
var var2 = methodIlGen.DeclareLocal(this.GetType());
methodIlGen.Emit(OpCodes.Stloc,var2);
////methodIlGen.EmitWriteLine(proxyField);
////methodIlGen.Emit(OpCodes.St);
//methodIlGen.Emit(OpCodes.Ldloc,var2);
methodIlGen.Emit(OpCodes.Call, this.GetType().GetMethods().First(x => x.Name == "HandleCall"));
有什么想法我在这里做错了吗?
Common Language Runtime detected an invalid program.
顺便说一句,我得到的错误是
JIT Compiler encountered an internal limitation.