How to dynamically call a method in C#?

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

    Use reflection - try the Type.GetMethod Method

    Something like

    MethodInfo addMethod = this.GetType().GetMethod("add");
    object result = addMethod.Invoke(this, new object[] { x, y } );
    

    You lose strong typing and compile-time checking - invoke doesn't know how many parameters the method expects, and what their types are and what the actual type of the return value is. So things could fail at runtime if you don't get it right.

    It's also slower.

提交回复
热议问题