简体   繁体   English

如何将任意方法(或委托)作为参数传递给函数?

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

I need to be able to pass an arbitrary method to some function myFunction : 我需要能够将任意方法传递给某个函数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. 还应该可以通过反射了解myFunction的实际参数数量及其类型。 What would be AnyFunc in the myFunction definition to accommodate such requirements? myFunction定义中的AnyFunc会满足这些要求吗? It is acceptible to have several overloaded versions of the myFunction . 有几个重载版本的myFunction是可以接受的。

The Delegate type is the supertype of all other delegate types: Delegate类型是所有其他委托类型的超类型:

void myFunction(Delegate func) { ... }

Then, func.Method will give you a MethodInfo object you can use to inspect the return type and parameter types. 然后, func.Method将为您提供一个MethodInfo对象,您可以使用它来检查返回类型和参数类型。

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. 你想要在更高层次上完成什么的一些想法会很好,因为这种方法可能不会是理想的。

Have the method accept a Delegate , rather than a particular delegate: 让方法接受Delegate ,而不是特定的委托:

void myFunction(Delegate func)
{

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM