C# 反射,經過類名、方法名調用方法[轉]

轉自:https://www.cnblogs.com/coderJiebao/p/CSharp09.htmlhtml

在 C# 代碼中,有些時候只知道方法的名字(string),須要調用該方法,那麼就須要用到 C# 的反射機制。下面是一個簡單的 demo。this

 

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

 

 

參數對比,spa

                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 });
                    }
                }
相關文章
相關標籤/搜索