我正在试验一个对象可以用来激发自己事件的扩展方法。将参数隐式转换为委托的扩展方法?
我已经得到它的工作几乎我想如何我可以改善它的参数传递的点可以转换为EventArgs的构造函数参数,而不诉诸激活。
我会说的前期,我很怀疑这是可能的,但我想给它一个镜头,因为有时我在编码技巧等都有很惊讶......
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));
}
}
感谢您花时间分享您的想法..发表这个问题值得! –