How to dynamically call a method in C#?

后端 未结 5 1070
醉话见心
醉话见心 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: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;
            }
        }
    }
    

提交回复
热议问题