[No000085]C#反射Demo,通過類名(String)創建類實例,通過方法名(String)調用方法


using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
class test
{
    public void Method()//1
    {
        Console.WriteLine("1:__" + "Method調用成功!");
    }
    public void Method(string str)//2
    {
        Console.WriteLine("2:__" + str);
    }

    public string Method(string str1, string str2)//3
    {
        string className1 = this.GetType().FullName;//非靜態方法中獲取類名
        string className2 = MethodBase.GetCurrentMethod().ReflectedType.FullName;//靜態方法中的獲取類名
        Console.WriteLine("3:__;類名"+className1+"_"+ className2);
        return "3:__" + str1 + str2;
    }
}
class Program
{
    public static void run(string testcase)
    {
        string strClass = "test";  //命名空間+類名
        string strMethod = "Method";//方法名

        Type type;
        object obj;

        type = Type.GetType(strClass);//通過string類型的strClass獲得同名類“type”
        obj = System.Activator.CreateInstance(type);//創建type類的實例 "obj"

        MethodInfo method = type.GetMethod(strMethod, new Type[] { });//取的方法描述//通過string類型的strMethod獲得同名的方法“method”//1
        method.Invoke(obj, null);//type類實例obj,調用方法"method"//1

        method = type.GetMethod(strMethod, new Type[] { typeof(String) });//取的方法描述//2
        object[] objs = new object[] { testcase };
        method.Invoke(obj, objs);//t類實例obj,調用方法"method(testcase)"//2

        method = type.GetMethod(strMethod, new Type[] { typeof(String), typeof(String) });//取的方法描述//2
        var result = (string)method.Invoke(obj, new object[] { "a", "b" });//3
        Console.WriteLine(result);//3

        //string className = this.GetType().FullName;
        string className = MethodBase.GetCurrentMethod().ReflectedType.FullName;//靜態方法中的獲取類名
        Console.WriteLine(className);
        Console.ReadKey();
    }
    static void Main(string[] args)
    {
        string testcase = "測試呀";//自己定義的類
        run(testcase);
    }
}

 


免責聲明!

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



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