C#通过反射,通过类名、方法名调用方法

using System;
using System.Reflection;

class Test
{
    // 无参数,无返回值方法
    public void Method()
    {
        Console.WriteLine("Method(无参数) 调用成功!");
    }

    // 有参数,无返回值方法
    public void Method(string str)
    {
        Console.WriteLine("Method(有参数) 调用成功!参数 :" + str);
    }

    // 有参数,有返回值方法
    public string Method(string str1, string str2)
    {
        Console.WriteLine("Method(有参数,有返回值) 调用成功!参数 :" + str1 + ", " + str2);
        string className = this.GetType().FullName;         // 非静态方法获取类名
        return className;
    }
}

class Program
{
    static void Main(string[] args)
    {
        string strClass = "Test";           // 命名空间+类名
        string strMethod = "Method";        // 方法名

        Type type;                          // 存储类
        Object obj;                         // 存储类的实例

        type = Type.GetType(strClass);      // 通过类名获取同名类
        obj = System.Activator.CreateInstance(type);       // 创建实例

        MethodInfo method = type.GetMethod(strMethod, new Type[] {});      // 获取方法信息
        object[] parameters = null;
        method.Invoke(obj, parameters);                           // 调用方法,参数为空

        // 注意获取重载方法,需要指定参数类型
        method = type.GetMethod(strMethod, new Type[] { typeof(string) });      // 获取方法信息
        parameters = new object[] {"hello"};
        method.Invoke(obj, parameters);                             // 调用方法,有参数

        method = type.GetMethod(strMethod, new Type[] { typeof(string), typeof(string) });      // 获取方法信息
        parameters = new object[] { "hello", "你好" };
        string result = (string)method.Invoke(obj, parameters);     // 调用方法,有参数,有返回值
        Console.WriteLine("Method 返回值:" + result);                // 输出返回值

        // 获取静态方法类名
        string className = MethodBase.GetCurrentMethod().ReflectedType.FullName;
        Console.WriteLine("当前静态方法类名:" + className);

        Console.ReadKey();
    }
}
BindingFlags  flag  =  BindingFlags.Public  |  BindingFlags.Instance;
ct  returnValue  =  method.Invoke(dObj,flag,Type.DefaultBinder,parameters,null);

参考:http://www.imooc.com/article/287955



原文地址:https://www.cnblogs.com/wangchuang/p/12202328.html