How to dynamically call a method in C#?

后端 未结 5 958
醉话见心
醉话见心 2020-12-07 21:07

I have a method:

  add(int x,int y)

I also have:

int a = 5;
int b = 6;
string s = \"add\";

Is it poss

5条回答
  •  有刺的猬
    2020-12-07 21:21

    If the functions are known at compile time and you just want to avoid writing a switch statement.

    Setup:

    Dictionary> functions =
      new Dictionary>();
    
    functions["add"] = this.add;
    functions["subtract"] = this.subtract;
    

    Called by:

    string functionName = "add";
    int x = 1;
    int y = 2;
    
    int z = functions[functionName](x, y);
    

提交回复
热议问题