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

转自:https://www.cnblogs.com/coderJiebao/p/CSharp09.html

在 C# 代码中,有些时候只知道方法的名字(string),需要调用该方法,那么就需要用到 C# 的反射机制。下面是一个简单的 demo。

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();
    }
}

参数对比,

                MethodInfo[] info = definedType.GetMethods();
                for (int i = 0; i < info.Length; i++)
                {
                    var md = info[i];
                    //方法名
                    string mothodName = md.Name;
                    //参数集合
                    ParameterInfo[] paramInfos = md.GetParameters();
                    //方法名相同且参数个数一样
                    if (mothodName == "ToString" && paramInfos.Length == 2)
                    {
                        var s = md.Invoke(obj, new object[] { "VE", null });
                    }
                }

猜你喜欢

转载自www.cnblogs.com/-sylar/p/10728696.html