如何访问作为参数传递给C#中的通用函数的对象的方法
我有一个generics方法,它有一些generics类型的参数。 我想要做的是,能够访问我的函数内的这个generics类型参数的方法。
public void dispatchEvent(T handler, EventArgs evt) { T temp = handler; // make a copy to be more thread-safe if (temp != null) { temp.Invoke(this, evt); } }
我希望能够在temp上调用Invoke方法,类型为T.有没有办法做到这一点?
谢谢。
您可能会更喜欢以下内容:
public void dispatchEvent(EventHandler handler, T evt) where T: EventArgs { if (handler != null) handler(this, evt); }
只是为了好玩,这里是一个扩展方法:
public static void Raise(this EventHandler handler, Object sender, T args) where T : EventArgs { if (handler != null) handler(sender, args); }
对generics使用约束:
public void dispatchEvent(T handler, EventArgs evt) where T : yourtype
这个怎么样 :
public void dispatchEvent(T handler, EventArgs evt) { T temp = handler; // make a copy to be more thread-safe if (temp != null && temp is Delegate) { (temp as Delegate).Method.Invoke((temp as Delegate).Target, new Object[] { this, evt }); } }