C# 程序集Assembly

原谅我到目前为止一直肤浅的认为程序集就是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的组成:
程序集 - 图1

   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类的对象。
  程序运行时,一个class对应一个Type类的对象。通过Type对象可以获得类的所有信息。
获得Type对象的方式:
  1. 通过类获得对应的Type
    Type t1 = typeof(Person);
  2. 通过对象获得Type
    Type t2 = person.GetType(); this.GetType();
  3. 用assembly对象,通过类的full name类获得type对象
程序集 - 图2
 Assembly ass1 = Assembly.LoadFrom(@”c:\users\xcao\documents\visual studio 2012\Projects\ConsoleApplication6\ConsoleApplication6\libs\Ecole.dll”);

  1. //GetType的参数一定要是full name的string

 Type tStu = ass1.GetType(“Ecole.Student”);

  1. object stu1 = Activator.CreateInstance(tStu);<br />![](https://cdn.nlark.com/yuque/0/2021/gif/12439570/1611715952105-352e4031-d974-4971-a423-00134c41c265.gif#align=left&display=inline&height=20&margin=%5Bobject%20Object%5D&originHeight=20&originWidth=20&size=0&status=done&style=none&width=20)<br />  4. 获得程序集中定义的所有的public类<br />    Type[] allPublicTypes = ass1.GetExportedTypes();<br />  5. 获得程序集中定义的所有的类<br />    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
Assembly.Load()方法,Assembly.LoadFrom()方法,Assembly.LoadFile()方法的差别