C#提供-------AttributeUsage使用

it2025-01-26  21

Assembly(c#中简单说明) Assembly(c#中简单说明) 2008-07-11 00:27

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

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              Country cy; 13              String assemblyName = @"NamespaceRef"; 14             string strongClassName = @"NamespaceRef.China"; 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 Country 24     { 25         public string name; 26      } 27 28     class Chinese : Country 29     { 30         public Chinese() 31         { 32              name = "你好"; 33          } 34      } 35 36     class America : Country 37     { 38         public America() 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一样有很多功能用于名称与方法和属性之间的转化。深入理解这两个类,你就可以清晰通用语言层是如何工作。

转载于:https://www.cnblogs.com/w-wfy/p/7668804.html

最新回复(0)