什么是Assembly(程序集)?

转自:http://hi.baidu.com/leyhui/blog/item/58de0559cbeead292934f0d8.html

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

1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 using System.Reflection; 5 6 namespace 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对象,以前我们只能这样来写代码:
1 if (strongClassName == " China " ) 2      cy = new China(); 3 else 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).
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值