原諒我到目前為止一直膚淺的認為程序集就是dll,這種想法是錯誤的。
今天就系統的學習記錄一下“程序集”的概念。原文鏈接https://www.cnblogs.com/czx1/p/201413137070-com.html
程序集包含了兩種文件:可執行文件(.exe文件)和 類庫文件(.dll文件)。
在VS開發環境中,一個解決方案可以包含多個項目,而每個項目就是一個程序集。
應用程序結構:包含 應用程序域(AppDomain),程序集(Assembly),模塊(Module),類型(Type),成員(EventInfo、FieldInfo、MethodInfo、PropertyInfo) 幾個層次。
他們之間是一種從屬關系,也就是說,一個AppDomain能夠包括N個Assembly,一個Assembly能夠包括N個Module,一個Module能夠包括N個Type,一個Type能夠包括N個成員。他們都在System.Reflection命名空間下。【公共語言運行庫CLR】加載器 管理 應用程序域,這種管理包括 將每個程序集加載到相應的應用程序域 以及 控制每個程序集中類型層次結構的內存布局。
從【應用程序結構】中不難看出程序集Assembly的組成:

MemberInfo 該類是一個基類,它定義了EventInfo、FieldInfo、MethodInfo、PropertyInfo的多個公用行為 。
一個程序運行起來以后,有一個應用程序域(AppDomain),在這個應用程序域(AppDomain)中放了我們用到的所有程序集(Assembly)。我們所寫的所有代碼都會編譯到【程序集】文件(.exe .dll)中,並在運行時以【Assembly對象】方式加載到內存中運行,每個類(Class Interface)以【Type對象】方式加載到內存,類的成員(方法,字段,屬性,事件,構造器)加載到內存也有相應的對象。
Assembly程序集對象 https://blog.csdn.net/CJB_King/article/details/80521481
Assembly 是一個抽象類,我們用的都是RuntimeAssembly的對象。
獲得程序集的方式:
1. 獲得當前【應用程序域】中的所有程序集
Assembly[] ass = AppDomain.CurrentDomain.GetAssemblies();
所有用到過得aessembly。如果只是add ref了,沒有在程序中用到,AppDomain.CurrentDomain.GetAssemblies()中沒有。用到時才被JIT加載到內存。
每個app都有一個AppDomain,OS不允許其他app訪問這個程序的AppDomain
2. 獲得當前對象所屬的類所在的程序集
this.GetType().Assembly;
Type對象肯定在一個assembly對象中
可以通過Type對象得到程序集。
3. 根據路徑加載程序集
Assembly.LoadFrom(assPath);
Type類型對象
Type 是一個抽象類,我們用的都是TypeInfo類的對象。
獲得Type對象的方式:
1. 通過類獲得對應的Type
Type t1 = typeof(Person);
2. 通過對象獲得Type
Type t2 = person.GetType(); this.GetType();
3. 用assembly對象,通過類的full name類獲得type對象
Assembly ass1 = Assembly.LoadFrom(@"c:\users\xcao\documents\visual studio 2012\Projects\ConsoleApplication6\ConsoleApplication6\libs\Ecole.dll"); //GetType的參數一定要是full name的string Type tStu = ass1.GetType("Ecole.Student");
object stu1 = Activator.CreateInstance(tStu);
4. 獲得程序集中定義的所有的public類
Type[] allPublicTypes = ass1.GetExportedTypes();
5. 獲得程序集中定義的所有的類
Type[] allTypes = ass1.GetTypes();
Type類的屬性:
t.Assembly; 獲取t所在的程序集
t.FullName; 獲取t所對應的類的full name
t.Name; 獲取t所對應的類的 name
t.IsArray; 判斷t是否是一個數組類
t.IsEnum; 判斷t是否是一個枚舉類
t.IsAbstract; 判斷t是否是一個抽象類
t.IsInterface; 判斷t是否是一個interface
Type類的方法:
notebookInterfaceType.IsAssignableFrom(Type t);判斷t是否實現了 notebookInterfaceType 接口
t.IsSubclassOf(Type parent); t是否是parent的子類
t.IsInstanceOfType(object o); o是否是t類的對象
t.GetFields(); //method, property 得到所有的public的fields,methods,properties
t.GetField("gender"); 根據名字得到某個field
