【发布时间】:2017-03-05 19:12:35
【问题描述】:
我正在尝试动态创建函数,在执行时只调用给定的 Func
public IProxifier<T> Override(string method, Func<T, object[], object> handler)
{
if (!overr.ContainsKey(method))
{
Ops op = new Ops();
op.GenericTypes = new Type[] { typeof(T) };
op.MethodInfo = handler.GetMethodInfo();
MethodBuilder mb = tb.DefineMethod(method, MethodAttributes.Public | MethodAttributes.ReuseSlot |
MethodAttributes.Virtual | MethodAttributes.HideBySig, typeof(object), new Type[] { typeof(object[]) });
ILGenerator il = mb.GetILGenerator();
//il.EmitCall(OpCodes.Callvirt, op.MethodInfo, op.GenericTypes);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Callvirt, handler.GetMethodInfo());
il.Emit(OpCodes.Ret);
overr.Add(method, op);
}
return this;
}
我正在使用反射创建一个动态类型,每次调用此 Override 方法时,我都需要在此动态创建的对象中创建给定的方法(覆盖现有的方法,即 ToString() )。
我已经以各种方式尝试了 Emit 和 EmitCall,但我得到的只是 InvalidProgramException 或什么都没有。
我想要实现的是:
- 对于给定的 Func,要覆盖一个方法,当它被调用时,这个 Func 会被触发并返回其结果,所有这些都使用 ILGenerator。我怎样才能做到这一点?我被困了好几天,没有任何效果。
【问题讨论】:
-
你能添加一些关于你打算如何使用它的代码吗?我认为这会澄清你的意图。
-
你可以试试
il.Emit(OpCodes.Callvirt, handler.GetMethodInfo());,而不是:il.Emit(OpCodes.Callvirt, typeof(Func<T, object[], object>).GetMethod("Invoke")); -
嗯,将参数压入堆栈呢?您调用的方法需要参数。比如
T和object[]之前的Callvirt
标签: c# system.reflection reflection.emit