且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-14 15:30:36

您需要传递一个 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"));