How to dynamically call a method in C#?

后端 未结 5 959
醉话见心
醉话见心 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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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<string, Func<int, int, int>> functions =
      new Dictionary<string, Func<int, int, int>>();
    
    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);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-07 21:35

    You can use reflection.

    using System;
    using System.Reflection;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                Program p = new Program();
                Type t = p.GetType();
                MethodInfo mi = t.GetMethod("add", BindingFlags.NonPublic | BindingFlags.Instance);
                string result = mi.Invoke(p, new object[] {4, 5}).ToString();
                Console.WriteLine("Result = " + result);
                Console.ReadLine();
            }
    
            private int add(int x, int y)
            {
                return x + y;
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题