我正在试验一个对象可以用来触发自己的事件的扩展方法。
我已经让它几乎按照我想要的方式工作,但我想知道我是否可以将它改进到可以将传递的参数转换为 EventArgs 的构造函数参数而无需求助于 Activator 的程度。
我会提前说我怀疑这是可能的,但我会试一试,因为有时我真的很惊讶其他人的编码技巧......
void Main()
{
var c = new C();
c.E += (s, e) => Console.WriteLine (e.Message);
c.Go();
}
public class C
{
public event EventHandler<Args> E;
public void Go()
{
Console.WriteLine ("Calling event E...");
// This version doesn't know the type of EventArgs so it has to use Activator
this.Fire(E, "hello");
// This version doesn't know ahead of time if there are any subscribers so it has to use a delegate
this.Fire(E, () => new Args("world"));
// Is there some way to get the best of both where it knows the type but can delay the
// creation of the event args?
//this.Fire<Args>("hello");
}
}
public class Args : EventArgs
{
public Args(string s)
{
Message = s;
}
public string Message { get; set; }
}
public static class Ext
{
public static void Fire<T>(this object source, EventHandler<T> eventHander, Func<T> eventArgs) where T : EventArgs
{
if (eventHander != null)
eventHander(source, eventArgs());
}
public static void Fire<T>(this object source, EventHandler<T> eventHander, params object[] args) where T : EventArgs
{
if (eventHander != null)
eventHander(source, (T)Activator.CreateInstance(typeof(T), args));
}
}