How to pass an arbitrary method (or delegate) as a parameter to a function?

I need to pass an arbitrary method to some myFunction function:

 void myFunction(AnyFunc func) { ... } 

It should be possible to execute it using other static, instances, public or private methods, or even delegates:

 myFunction(SomeClass.PublicStaticMethod); myFunction(SomeObject.PrivateInstanceMethod); myFunction(delegate(int x) { return 5*x; }); 

The passed method can have any number of parameters and any type of return. It should also be possible to find out the actual number of parameters and their types in myFunction through reflection. What would AnyFunc in myFunction definition to satisfy such requirements? It is permissible to have several overloaded versions of myFunction .

+7
source share
2 answers

The Delegate type is a supertype of all other delegate types:

 void myFunction(Delegate func) { ... } 

Then func.Method will provide you with a MethodInfo object that you can use to check return types and parameter types.

When calling a function, you need to explicitly specify which type of delegate you want to create:

 myFunction((Func<int, int>) delegate (int x) { return 5 * x; }); 

Some idea of ​​what you are trying to accomplish at a higher level would be good, as this approach may not be ideal.

+6
source

Ask the method to accept a Delegate , not a specific delegate:

 void myFunction(Delegate func) { } 
0
source

All Articles