How to access the method of an object that is passed as a parameter to a common function in C #

I have a generic method that has some generic type parameter. What I want to do is access to the method of this type parameter of a type inside my function.

public void dispatchEvent<T>(T handler, EventArgs evt) { T temp = handler; // make a copy to be more thread-safe if (temp != null) { temp.Invoke(this, evt); } } 

I want to be able to call the Invoke method for temp, which is of type T. Is there a way to do this?

Thanks.

+2
source share
3 answers

Perhaps you are after something else:

  public void dispatchEvent<T>(EventHandler<T> handler, T evt) where T: EventArgs { if (handler != null) handler(this, evt); } 

Just for fun, here it is like 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); } 
+2
source

Use a constraint for the generic type:

 public void dispatchEvent<T>(T handler, EventArgs evt) where T : yourtype 
+5
source

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 }); } } 
0
source

Source: https://habr.com/ru/post/1314584/


All Articles