Chamar um método quando ocorrer um evento genérico
Estou enfrentando um problema ao tentar implementar uma chamada para um método acionado por um evento que deve ser definido durante o tempo de execução. Encontrei esta resposta:
Redirecionando para um método dinâmico de um manipulador de eventos genérico
e implementei essa solução, mas continuo recebendo uma exceção quando o método de chamada é uma instância, não estática. Aqui está o meu código parcial:
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;
}
}
Não consigo encontrar uma maneira de me livrar dessa exceção, o código funciona bem se eu ligarSetFlag () método estático, mas não é disso que eu preciso. Todas as sugestões serão muito apreciadas. Desde já, obrigado.