如何传递任何方法作为另一个函数的参数 [英] how to pass any method as a parameter for another function
问题描述
在A类中,我有
internal void AFoo(string s, Method DoOtherThing)
{
if (something)
{
//do something
}
else
DoOtherThing();
}
现在我需要能够通过 DoOtherThing
到 AFoo()
。我的要求是 DoOtherThing
可以有返回类型的任何签名几乎总是无效的。 B类的这样的东西,
Now I need to be able to pass DoOtherThing
to AFoo()
. My requirement is that DoOtherThing
can have any signature with return type almost always void. Something like this from Class B,
void Foo()
{
new ClassA().AFoo("hi", BFoo);
}
void BFoo(//could be anything)
{
}
我知道我可以用 Action
或通过实施代理(如许多其他SO帖子)所示,但是如果B类函数的签名未知,那么如何才能实现?
I know I can do this with Action
or by implementing delegates (as seen in many other SO posts) but how could this be achieved if signature of the function in Class B is unknown??
推荐答案
您需要传递一个 delegate
instance; Action
可以正常工作:
You need to pass a delegate
instance; Action
would work fine:
internal void AFoo(string s, Action doOtherThing)
{
if (something)
{
//do something
}
else
doOtherThing();
}
如果 BFoo
无参数,它将以您的示例的方式工作:
If BFoo
is parameterless it will work as written in your example:
new ClassA().AFoo("hi", BFoo);
如果需要参数,您需要提供:
If it needs parameters, you'll need to supply them:
new ClassA().AFoo("hi", () => BFoo(123, true, "def"));
这篇关于如何传递任何方法作为另一个函数的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!