需要实现这样的功能:监测程序中event触发的情况,事先约定event按照这样的方式定义:
EventHandler<T> MyEvent
假设一个类定义如下:
public class EventEmitter
{
public class MyEventArgs : EventArgs
{
}
public event EventHandler<T> MyEvent;
public void Emit()
{
OnMyEvent();
}
protected void OnMyEvent()
{
var myEventHandler = MyEvent;
if (myEventHandler != null)
{
myEventHandler(this, new MyEventArgs());
}
}
}
监测类定义如下:
public class EventWatcher
{
public void SetProbe(object target, string eventName, Action<EventArgs> action) {
var eventInfo = target.GetType().GetEvent(eventName);
eventInfo.GetAddMethod().Invoke(target, new object[] { new EventHandler((sender, e) => {
action(e);
})});
}
}
调用过程如下:
var watcher = new EventWatcher();
var emitter = new EventEmitter();
watcher.SetProbe(emitter, "MyEvent", (e) =>
{
Console.WriteLine(String.Format("{0} is emitted", e.GetType()));
});
emitter.Emit();
Console.Read();
编程OK,但是运行的时候报错:
现在能够想到的就是规定Event按照如下方式定义:
EventHandler MyEvent
而不使用泛型,但是这样终究不爽,有什么办法可以解决吗?