Pass Method as Parameter using C#

后端 未结 12 1530
不知归路
不知归路 2020-11-21 23:30

I have several methods all with the same parameter types and return values but different names and blocks. I want to pass the name of the method to run to another method tha

12条回答
  •  滥情空心
    2020-11-22 00:11

    You should use a Func delegate, that represents a function taking a string argument and returning an int value:

    public bool RunTheMethod(Func myMethod)
    {
        // Do stuff
        myMethod.Invoke("My String");
        // Do stuff
        return true;
    }
    

    Then invoke it this way:

    public bool Test()
    {
        return RunTheMethod(Method1);
    }
    

提交回复
热议问题