如何将任何方法作为另一个函数的参数传递 [英] how to pass any method as a parameter for another function

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

问题描述

在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 实例;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屋!

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