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

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

问题描述

我需要能够通过任意方法的一些功能 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的的参数和它们的类型的实际数目。什么是 AnyFunc myFunction的定义,以适应这样的要求?这是acceptible有 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.

推荐答案

代表类型的所有其他委托类型的超类型:

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天全站免登陆