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




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM