当我试图实现对应该在运行时定义的事件触发的方法的调用时,我遇到了一个问题。我找到了这个答案:
从通用事件处理程序重定向到动态方法
并实现了该解决方案,但当要调用的方法是实例方法而不是静态方法时,我总是得到一个异常。这是我的部分代码:
public class Operation
{
public bool EventFired
{
get { return _eventFired; }
}
private bool _eventFired = false;
public void Execute(object source, string EventName)
{
EventInfo eventInfo = source.GetType().GetEvent(EventName);
Delegate handler = null;
Type delegateHandler = eventInfo.EventHandlerType;
MethodInfo invokeMethod = delegateHandler.GetMethod("Invoke");
ParameterInfo[] parms = invokeMethod.GetParameters();
Type[] parmTypes = new Type[parms.Length];
for (int i = 0; i < parms.Length; i++)
parmTypes[i] = parms[i].ParameterType;
DynamicMethod customMethod = new DynamicMethod
(
"TempMethod",
invokeMethod.ReturnType,
parmTypes,
typeof (Operation).Module
);
MethodInfo inf = typeof (Operation).GetMethod("SetFlag", BindingFlags.Instance | BindingFlags.Public);
ILGenerator ilgen = customMethod.GetILGenerator();
ilgen.Emit(OpCodes.Ldarg_0);
ilgen.Emit(OpCodes.Call, inf);
ilgen.Emit(OpCodes.Ret);
//handler = _customMethod.CreateDelegate(delegateHandler); // This works if I change SetFlag() to static
handler = customMethod.CreateDelegate(delegateHandler, this); // I get an ArgumentException at this point:
//Cannot bind to the target method because its signature
//or security transparency is not compatible with that of the delegate type.
eventInfo.AddEventHandler(source, handler);
}
/// <summary>Signals that the event has been raised.</summary>
public void SetFlag()
{
_eventFired = true;
}
}
我找不到摆脱该异常的方法,如果我将SetFlag()方法转为静态,代码会正常工作,但这不是我需要的。如有任何建议,我们将不胜感激。提前谢谢。
我最终通过稍微修改DynamicMethod定义解决了这个问题,如以下答案所述:
参考';这';在动态事件处理程序中
如果我将我的类类型添加为type数组中的第一个值,然后将其作为参数传递给DynamicMethod,则会正确创建委托,并且它可以与实例方法一起使用!
public class Operation
{
public bool EventFired
{
get { return _eventFired; }
}
private bool _eventFired = false;
public void Execute(object source, string EventName)
{
EventInfo eventInfo = source.GetType().GetEvent(EventName);
Delegate handler = null;
Type delegateHandler = eventInfo.EventHandlerType;
MethodInfo invokeMethod = delegateHandler.GetMethod("Invoke");
ParameterInfo[] parms = invokeMethod.GetParameters();
Type[] parmTypes = new Type[parms.Length + 1];
parmTypes[0] = this.GetType(); //First parameter is this class type.
for (int i = 0; i < parms.Length; i++)
parmTypes[i + 1] = parms[i].ParameterType;
DynamicMethod customMethod = new DynamicMethod
(
"TempMethod",
invokeMethod.ReturnType,
parmTypes
);
MethodInfo inf = typeof (Operation).GetMethod("SetFlag", BindingFlags.Instance | BindingFlags.Public);
ILGenerator ilgen = customMethod.GetILGenerator();
ilgen.Emit(OpCodes.Ldarg_0);
ilgen.Emit(OpCodes.Call, inf);
ilgen.Emit(OpCodes.Ret);
handler = customMethod.CreateDelegate(delegateHandler, this);
eventInfo.AddEventHandler(source, handler);
}
/// <summary>Signals that the event has been raised.</summary>
public void SetFlag()
{
_eventFired = true;
}
}