C# 調用程序集方法


  • 加載程序集 (Assembly類)

使用 Assembly 類可以加載程序集、瀏覽程序集的元數據和構成部分、發現程序集中包含的類型以及創建這些類型的實例

    // 加載該路徑的程序集
    Assembly ass = Assembly.LoadFrom(@"C:\Users\肖黎望\Desktop\net練習\ConsoleApplication1\Animal\bin\Debug\Animal.dll");
  • 獲得該程序集內所有文件的 Type (Type類),通過Type對象可以獲得類的信息(類名、命名空間、方法、屬性....)

反射的核心類-Type,封裝了關於類型的元數據,是進行反射的入口。當獲得了類型的Type對象后,可以根據Type提供的書信和方法獲得這個類型的一切信息,包括字段,屬性,事件,參數,構造函數等

            //GetTypes 獲得該程序集下所有類的Type
            Type[] tps = ass.GetTypes(); //獲得所有公共類型
            Type[] tps = ass.GetExportedTypes(); //通過指定類名獲取該類的 Type

            foreach (Type tp in tps) { //命名空間.類名
 Console.WriteLine(tp.FullName); //類名
 Console.WriteLine(tp.Name); //所有方法的信息 數組
                MethodInfo[] meths = tp.GetMethods(); //MethodInfo 保存方法的所有信息
                foreach (MethodInfo meth in meths) { //獲得方法名
 Console.WriteLine(meth.Name); } }

我們來看一下Type給我們提供的一些方法:

            Type cat_type = ass.GetType("Animal.Cat"); Type animal_type = ass.GetType("Animal.Animal"); //IsAssignableFrom 判斷 animal_type 是不是 cat_type 的父類
            animal_type.IsAssignableFrom(cat_type); //返回 TRUE //IsSubclassOf 判斷是不是 animal_type 的子類
            cat_type.IsSubclassOf(animal_type); //返回TRUE
 Object obj = Activator.CreateInstance(cat_type); //IsInstanceOfType 判斷obj是不是cat_type 的對象
            cat_type.IsInstanceOfType(obj); //返回TRUE //判斷obj是不是animal_type 的對象
            animal_type.IsInstanceOfType(obj); //返回TRUE
  • 創建對象(Activator類)
        object obj = Activator.CreateInstance(cat_type);
  • 調用方法
            Type cat_type = ass.GetType("Animal.Cat");
            
            //創建對象
            object obj = Activator.CreateInstance(cat_type);
            //獲取屬性
            PropertyInfo prop = cat_type.GetProperty("Food");
            //設置屬性
            prop.SetValue(obj, "");
            //獲取方法
            MethodInfo meth = cat_type.GetMethod("eat");
            //設置參數,如果沒有設置 null,調用方法
            meth.Invoke(obj,null);

 


免責聲明!

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



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