How to pass an arbitrary method (or delegate) as p

2019-06-17 02:38发布

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

void myFunction(AnyFunc func) { ... }

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

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

Passed method may have any number of parameters and any return type. It should also be possible to learn the actual number of parameters and their types in myFunction via reflection. What would be AnyFunc in the myFunction definition to accommodate such requirements? It is acceptible to have several overloaded versions of the myFunction.

2条回答
迷人小祖宗
2楼-- · 2019-06-17 02:47

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

void myFunction(Delegate func) { ... }

Then, func.Method will give you a MethodInfo object you can use to inspect the return type and parameter types.

When calling the function you will have 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're trying to accomplish at a higher level would be good, as this approach may not turn out to be ideal.

查看更多
走好不送
3楼-- · 2019-06-17 03:02

Have the method accept a Delegate, rather than a particular delegate:

void myFunction(Delegate func)
{

}
查看更多
登录 后发表回答