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

别说谁变了你拦得住时间么 提交于 2019-12-23 08:17:43

问题


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.


回答1:


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.




回答2:


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

void myFunction(Delegate func)
{

}


来源:https://stackoverflow.com/questions/15931306/how-to-pass-an-arbitrary-method-or-delegate-as-parameter-to-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!