如何将任意方法(或委托)作为参数传递给函数? [英] How to pass an arbitrary method (or delegate) as parameter to a function?

查看:180
本文介绍了如何将任意方法(或委托)作为参数传递给函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够传递任意方法到一些函数 myFunction

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; });

传递的方法可能有任意数量的参数和任何返回类型。还可以通过反思了解 myFunction 中的实际参数数量及类型。 myFunction 定义中的 AnyFunc 将适应此类要求?可以接受 myFunction 的几个重载版本。

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.

推荐答案

delegate type是所有其他委托类型的超类型:

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

void myFunction(Delegate func) { ... }

然后, func.Method 将给你一个 MethodInfo 对象,您可以使用它来检查返回类型和参数类型。

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.

这篇关于如何将任意方法(或委托)作为参数传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆