我正在試驗一個對象可以用來激發自己事件的擴展方法。將參數隱式轉換爲委託的擴展方法?
我已經得到它的工作幾乎我想如何我可以改善它的參數傳遞的點可以轉換爲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));
}
}
感謝您花時間分享您的想法..發表這個問題值得! –