如何动态订阅事件? [英] How to dynamically subscribe to an event?
问题描述
相关
我需要检测当一个事件被触发。要做到这一点,我想动态的订阅的事件。
I need to detect when an event is fired. To do so I am trying to subscribe dynamically on the event.
现在的问题是,我有不同类型的代表,并非所有的事件具有相同的签名。提供的解决方案在这里和的here 预计对象发件人,EventArgs的
,而我没有使用,所以我得到一个异常告诉类型不匹配。
The problem is that I have different types of delegates, not all events have the same signature. The solutions provided in here and here expects object sender, EventArgs e
, which I am not using, so I get an exception telling the types doesn't match.
下面是一个代表一些例子,我有:
Here are some examples of a delegates I have:
public delegate void OnEventA(int id);
public delegate void OnEventB(double num, string name);
我怎样才能建立正确的代表?
How can I create the correct delegate?
推荐答案
经过一番研究,我发现了一些文章:
After some research I found some articles:
- How to: Hook Up a Delegate Using Reflection
- Delegate.CreateDelegate Method (Type, Object, MethodInfo, Boolean)
这让我明白了什么,我试图做我应该做的。
It helped me to understand what I was trying to do and I should do.
我需要使用 Delegate.CreateDelegate
通过了 EventHandlerType
(该事件的类型,委托)一类和方法(在previous参数从类)的方法的信息将处理该事件的一个实例。目标是激发此事件的控制。
I need to use Delegate.CreateDelegate
passing the EventHandlerType
(the type of the event, the delegate), a instance of a class and the method info of the method (from the class in the previous parameter) that will handle the event. Target is the control that fires this event.
Delegate handler = Delegate.CreateDelegate(evt.EventHandlerType, abc, mi1, false);
evt.AddEventHandler(target, handler);
进一步深挖导致我这个方法。我可以订阅使用lambda EX pression事件。使用<一个href="http://stackoverflow.com/questions/3781604/passing-a-lambda-to-a-method-with-diferent-parameters"><$c$c>Action<T>$c$c>我可以与不同类型和参数的数字订阅。
Further digging lead me to this method. I can subscribe to events using lambda expression. Using Action<T>
I can subscribe with different types and numbers of parameters.
public static Delegate Create<T>(EventInfo e, Action<T> a)
{
var parameters = e.EventHandlerType.GetMethod("Invoke").GetParameters().Select(p => Expression.Parameter(p.ParameterType, "p")).ToArray();
var exp = Expression.Call(Expression.Constant(a), a.GetType().GetMethod("Invoke"), parameters);
var l = Expression.Lambda(exp, parameters);
return Delegate.CreateDelegate(e.EventHandlerType, l.Compile(), "Invoke", false);
}
使用此方法(e为EventInfo;放到EventManager是类与上面的静态方法)
Using this method (e is the EventInfo; EventManager is the class with the static method above)
e.AddEventHandler(this, EventManager.Create<int>(e, (x) => Console.WriteLine("Execute")));
这篇关于如何动态订阅事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!