Calling an object of class System.Delegate in C #

I am trying to create an object that uses System.ComponentModel.ISynchronizeInvoke, which has a method: (among others)

public object Invoke(Delegate method, object[] args) 

What is the best way to call a method with given arguments? I can use:

  public object Invoke(Delegate method, object[] args) { return method.DynamicInvoke(args); } 

But it's late. My gut instinct is that this is the only way to name a method. Any ideas?

+6
source share
1 answer

I think that it is logically impossible for him in any other way. The delegate method can encapsulate a method of any signature (with any number and type of parameters and any type of return value or void). The only way to resolve your signature and call it using the arguments given (after checking that theyre the correct size and type) will be at run time through reflection.

If you did not implement the ISynchronizeInvoke interface and could not define your own method, you can limit your argument to method only to accept delegates of a particular signature method; in this case, you can refer to them directly.

For example, to execute methods that take no parameters and have a return value, you should use:

 public TResult Invoke<TResult>(Func<TResult> method) { return method(); } 

To execute a method that takes three parameters and has no return value, you should use:

 public void Invoke<T1,T2,T3>(Action<T1,T2,T3> method, T1 arg1, T2 arg2, T3 arg3) { method(arg1, arg2, arg3); } 
+4
source

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


All Articles