短发全头小卷发型图片:C#如何生成多文件程序集

来源:百度文库 编辑:偶看新闻 时间:2024/05/05 11:09:54
本节说明用于创建多文件程序集的过程,并提供阐释该过程中每个步骤的完整示例。
创建多文件程序集
将包含程序集中其他模块引用的命名空间的所有文件编译成代码模块。代码模块的默认扩展名为 .netmodule。例如,如果名为 Stringer 的文件创建名为 myStringer 的命名空间(在 Client 文件代码中引用),则应先将 Stringer 编译成代码模块。
编译所有其他模块,使用必要的编译器选项来表明代码中引用的其他模块。
使用程序集链接器 (Al.exe) 来创建包含程序集清单的输出文件。此文件包含作为程序集组成部分的所有模块或资源的参考信息。
注意
用于 C# 和 Visual Basic 的 Visual Studio 2005 IDE 只能用于创建单文件程序集。如果要创建多文件程序集,必须使用命令行编译器或带有 Visual C++ 的 Visual Studio 2005。
下面的示例通过编译包含其他文件所引用的命名空间的文件,来阐释上述过程的步骤 1。此示例开始时是 Stringer 文件的一些简单代码,Stringer 具有名为 myStringer 的命名空间(带有名为 Stringer 的类)。Stringer 类包含名为 StringerMethod 的方法,此方法将单独一行写入控制台。
// Assembly building example in the .NET Framework.
using System;
namespace myStringer
{
public class Stringer
{
public void StringerMethod()
{
System.Console.WriteLine("This is a line from StringerMethod.");
}
}
}
使用下面的命令编译此代码:
csc /t:module Stringer.cs
使用 /t: 编译器选项指定 module 参数,表明文件应作为模块(而不是作为程序集)编译。编译器生成名为 Stringer.netmodule 的模块,该模块可添加到程序集。
在上述过程的第二步中,必须编译包含对其他模块的引用的模块。此步骤使用 /addmodule 编译器选项。在下面的示例中,名为 Client 的代码模块具有入口点 Main 方法,此方法引用步骤 1 中创建的 Stringer.dll 模块中的方法。
下面的示例说明了 Client 的代码。
using System;
using myStringer; //The namespace created in Stringer.netmodule.
class MainClientApp
{
// Static method Main is the entry point method.
public static void Main()
{
Stringer myStringInstance = new Stringer();
Console.WriteLine("Client code executes");
//myStringComp.Stringer();
myStringInstance.StringerMethod();
}
}
使用下面的命令编译此代码:
csc /addmodule:Stringer.netmodule /t:module Client.cs
指定 /t:module 选项,因为此模块将在以后的步骤中添加到程序集。指定 /addmodule 选项,因为 Client 中的代码引用 Stringer.netmodule 中的代码创建的命名空间。编译器生成名为 Client.netmodule 的模块,它包含对另一模块 Stringer.netmodule 的引用。
注意
C# 和 Visual Basic 编译器支持使用以下两种不同语法直接创建多文件程序集。
两次编译创建出一个双文件程序集:
csc /t:module Stringer.cs
csc Client.cs /addmodule:Stringer.netmodule
一次编译创建出一个双文件程序集:
csc /out:Client.exe Client.cs /out:Stringer.netmodule Stringer.cs
您可以使用程序集链接器 (Al.exe) 从一组编译的代码模块中创建程序集。
使用“程序集链接器”创建多文件程序集
在命令提示处,键入下列命令:
al … /main: /out: /target:
在此命令中,“模块名”参数指定程序集要包含的各模块的名称。/main: 选项指定作为程序集入口点的方法名称。/out: 选项指定输出文件的名称,它包含程序集元数据。/target: 选项指定程序集是控制台应用程序可执行文件 (.exe)、Windows 可执行文件 (.win) 或库文件 (.lib)。
在下面的示例中,Al.exe 创建一个程序集,该程序集是一个控制台应用程序可执行文件,名为 myAssembly.exe。该应用程序包括名为 Client.netmodule 和 Stringer.netmodule 的两个模块,以及只包含程序集元数据的名为 myAssembly.exe 的可执行文件。程序集的入口点是位于 Client.dll 中的 MainClientApp 类中的 Main 方法
al Client.netmodule Stringer.netmodule /main:MainClientApp.Main /out:myAssembly.exe /target:exe
您可以使用 MSIL 反汇编程序 (Ildasm.exe) 来检查程序集的内容,或者确定文件是程序集还是模块。