How to dynamically call a method in C#?

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

    @Richard's answer is great. Just to expand it a bit:

    This can be useful in a situation where you dynamically created an object of unknown type and need to call its method:

    var do = xs.Deserialize(new XmlTextReader(ms)); // example - XML deserialization
    do.GetType().GetMethod("myMethodName").Invoke(do, new [] {arg1, arg2});
    

    becasue at compile time do is just an Object.

提交回复
热议问题