I have a generic method that has some parameter of a generic Type. What I want to do, is be able to access the method on this generic type parameter inside my function.
public void dispatchEvent<T>(T handler, EventArgs evt)
{
T temp = handler; // make a copy to be more thread-safe
if (t开发者_Go百科emp != null)
{
temp.Invoke(this, evt);
}
}
I want to be able to call the Invoke method on temp, which is of type T. Is there a way to do this?
Thank You.
Use a constraint for the generic:
public void dispatchEvent<T>(T handler, EventArgs evt) where T : yourtype
You might be after something more like:
public void dispatchEvent<T>(EventHandler<T> handler, T evt)
where T: EventArgs
{
if (handler != null)
handler(this, evt);
}
Just for fun, here it is as an extension method:
public static void Raise<T>(this EventHandler<T> handler, Object sender, T args)
where T : EventArgs
{
if (handler != null)
handler(sender, args);
}
How about this :
public void dispatchEvent<T>(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 });
}
}
精彩评论