Pass Method as Parameter using C#

后端 未结 12 1388
不知归路
不知归路 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:36

    From OP's example:

     public static int Method1(string mystring)
     {
          return 1;
     }
    
     public static int Method2(string mystring)
     {
         return 2;
     }
    

    You can try Action Delegate! And then call your method using

     public bool RunTheMethod(Action myMethodName)
     {
          myMethodName();   // note: the return value got discarded
          return true;
     }
    
    RunTheMethod(() => Method1("MyString1"));
    

    Or

    public static object InvokeMethod(Delegate method, params object[] args)
    {
         return method.DynamicInvoke(args);
    }
    

    Then simply call method

    Console.WriteLine(InvokeMethod(new Func(Method1), "MyString1"));
    
    Console.WriteLine(InvokeMethod(new Func(Method2), "MyString2"));
    

提交回复
热议问题