如何将任何方法作为另一个函数的参数传递

naw*_*fal 1 c# methods delegates parameter-passing

在A级,我有

internal void AFoo(string s, Method DoOtherThing)
{
    if (something)
    {
        //do something
    }
    else
        DoOtherThing();
}
Run Code Online (Sandbox Code Playgroud)

现在我需要能够传递DoOtherThingAFoo().我的要求是,DoOtherThing任何具有返回类型的签名几乎总是无效的.来自B级的东西,

void Foo()
{
    new ClassA().AFoo("hi", BFoo);
}

void BFoo(//could be anything)
{

}
Run Code Online (Sandbox Code Playgroud)

我知道我可以通过Action或通过实现代表来实现这一点(如许多其他SO帖子中所见)但如果B类中的函数签名未知,怎么能实现呢?

Mar*_*ell 9

你需要传递一个delegate实例; Action会工作正常:

internal void AFoo(string s, Action doOtherThing)
{
    if (something)
    {
        //do something
    }
    else
        doOtherThing();
}
Run Code Online (Sandbox Code Playgroud)

如果BFoo是无参数的,它将按照您的示例中的说明工作:

new ClassA().AFoo("hi", BFoo);
Run Code Online (Sandbox Code Playgroud)

如果它需要参数,您需要提供它们:

new ClassA().AFoo("hi", () => BFoo(123, true, "def"));
Run Code Online (Sandbox Code Playgroud)