《CLR Via C# 第3版》笔记之(二) - 响应文件

主要内容:

  1. 默认的响应文件
  2. 自定义响应文件

1. 默认的响应文件

.net在编译的时候会引用很多其他的程序集,最基本的比如System.dll,System.core.dll等等。

我们通过命令行编译的c#程序的时候并没有指定关联这些dll,那么它们是怎么关联的呢?

首先,新建一个Program.cs文件,内容如下(只引用了System):

using System;

namespace CLRViaCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("CLR via c#");
        }
    }
}

然后在命令行中编译此文件并运行。

D:\>csc /t:exe /out:p1.exe Program.cs
Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1
Copyright (C) Microsoft Corporation. All rights reserved.


D:\>p1.exe
CLR via c#

D:\>csc /t:exe /out:p2.exe /r:System.dll  Program.cs
Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1
Copyright (C) Microsoft Corporation. All rights reserved.


D:\>p2.exe
CLR via c#

从上面可以看出,无论是否引用System.dll,Program.cs都能正确编译并运行。

原来csc.exe在编译时会读取csc.exe所在文件夹里的文件csc.rep,即响应文件。

此响应文件中导入了一些常用的dll,所以我们编译时不用再引入了。

csc.rep的位置:C:\Windows\Microsoft.NET\Framework64\v4.0.30319

2. 自定义响应文件

如果引用了响应文件中不包含的dll(比如Microsoft.Build.dll),不指定 /r: 选项的话就无法编译。

将Program.cs改为如下内容

using System;
using Microsoft.Build.Execution;

namespace CLRViaCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(BuildResultCode.Success);
            Console.WriteLine("CLR via c#");
        }
    }
}

在命令行中编译并运行

D:\>csc /t:exe /out:p.exe  Program.cs
Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1
Copyright (C) Microsoft Corporation. All rights reserved.

Program.cs(2,17): error CS0234: The type or namespace name 'Build' does not
        exist in the namespace 'Microsoft' (are you missing an assembly
        reference?)

D:\>csc /t:exe /out:p.exe /r:Microsoft.Build.dll  Program.cs
Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1
Copyright (C) Microsoft Corporation. All rights reserved.


D:\>p.exe
Success
CLR via c#

如果引用的dll过多,也可以指定自己的响应文件,比如myresponse.rep。

里面只有一行内容:/r:Microsoft.Build.dll

响应文件myresponse.rep与Program.cs放在同一文件夹。

D:\>csc /t:exe /out:p.exe @myresponse.rep  Program.cs
Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1
Copyright (C) Microsoft Corporation. All rights reserved.


D:\>p.exe
Success
CLR via c#
posted @ 2011-04-18 22:32  wang_yb  阅读(1260)  评论(2编辑  收藏  举报