How to dynamically call a method in C#?

后端 未结 5 1045
醉话见心
醉话见心 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:28

    how can i do this in c#?

    Using reflection.

    add has to be a member of some type, so (cutting out a lot of detail):

    typeof(MyType).GetMethod("add").Invoke(null, new [] {arg1, arg2})
    

    This assumes add is static (otherwise first argument to Invoke is the object) and I don't need extra parameters to uniquely identify the method in the GetMethod call.

提交回复
热议问题