什么是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
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
}
using System;2
using System.Collections.Generic;3
using System.Text;4
using System.Reflection;5

6
namespace NamespaceRef7


{8
class Program9

{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 Country24

{25
public
string name;26
}27

28
class Chinese : Country29

{30
public Chinese()31

{32
name
= "你好";33
}34
}35

36
class America : Country37

{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();
那么如果我们有很长的一系列对象要创建,这样的代码维护起来是很困难的,而且也不容易阅读。现在我们可以通过在外部文件定义类的程序集名称和类的强名称来获得这样一个实例,即易于理解,又增强了扩展性还不用修改代码。
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一样有很多功能用于名称与方法和属性之间的转化。深入理解这两个类,你就可以清晰通用语言层是如何工作。
本文介绍了.NET框架中的Assembly(程序集),解释了其如何帮助开发者通过程序集信息获取类和实例等编程所需信息,并通过示例代码展示了如何使用Assembly类加载程序集并创建实例。
626

被折叠的 条评论
为什么被折叠?



