什么是Assembly(程序集)?

来源:互联网 发布:ddiction动作数据 编辑:程序博客网 时间:2024/05/08 02:39
转自:http://hi.baidu.com/leyhui/blog/item/58de0559cbeead292934f0d8.html

什么是Assembly(程序集)? Assembly是一个包含来程序的名称,版本号,自我描述,文件关联关系和文件位置等信息的一个集合。在.net框架中通过Assembly类来支持,该类位于System.Reflection下,物理位置位于:mscorlib.dll。 Assembly能干什么? 我们可以通过Assembly的信息来获取程序的类,实例等编程需要用到的信息。 一个简单的演示实例: 1.建立一个Console工程名为:NamespaceRef 2.写入如下代码:

1using System; 2using System.Collections.Generic; 3using System.Text; 4using System.Reflection; 5 6namespace NamespaceRef 7{ 8    class Program 9    { 10        static void Main(string[] args) 11        { 12             Person cy; 13             String assemblyName = @"NamespaceRef"; 14            string strongClassName = @"NamespaceRef.Chinese"; 15            // 注意:这里类名必须为强类名 16            // assemblyName可以通过工程的AssemblyInfo.cs中找到 17             cy = (Country)Assembly.Load(assemblyName).CreateInstance(strongClassName); 18             Console.WriteLine(cy.name); 19             Console.ReadKey(); 20         } 21     } 22 23    class Person 24    { 25        public string name; 26     } 27 28    class Chinese : Person 29    { 30        public Chinese() 31        { 32             name = "你好"; 33         } 34     } 35 36    class American : Person 37    { 38        public American() 39        { 40             name = "Hello"; 41         } 42     } 43}
由于Assembly的存在给我们在实现设计模式上有了一个更好的选择。 我们在开发的时候有时候会遇到这样的一个问题,根据对应的名称来创建指定的对象。如:给出chinese就要创建一个chinese对象,以前我们只能这样来写代码:
1if (strongClassName == "China") 2     cy = new China(); 3else if (strongClassName == "America") 4     cy = new America();
那么如果我们有很长的一系列对象要创建,这样的代码维护起来是很困难的,而且也不容易阅读。现在我们可以通过在外部文件定义类的程序集名称和类的强名称来获得这样一个实例,即易于理解,又增强了扩展性还不用修改代码。 cy = (Country)Assembly.Load(assemblyName).CreateInstance(strongClassName); 结论 Assembly类有很多的方法和属性,它和Type一样有很多功能用于名称与方法和属性之间的转化。深入理解这两个类,你就可以清晰通用语言层是如何工作。in the c# language there are these several conceps:program,types,members,namespace, and assembly. the difference between them is: program is consist of source files. source files could contain types(such as classes and interfaces) which may have some members(such as property, methods, fields, and events). types can be orgnized under the namespaces. when the program is compiled it is in an assembly(such as .exe or .dll).