如何使用 C# 6.0 为 .NET 2.0 编译?

How do I compile for .NET 2.0 with C# 6.0?

Visual Studio 2015 使用新的 c# 编译器编译旧的 CLR 没有问题。它似乎在幕后使用了 VBCSCompiler.exe,但我找不到任何关于 VBCSCompiler.exe 命令行选项的文档。

另一方面,csc.exe 似乎没有 select 目标 CLR 的选项。您可以使用最新的 csc.exe 为 CLR 4 编译,或者您可以使用较旧的 csc.exe 为 CLR 2 编译,但它不会是 C# 6。

那么如何针对 CLR 2 和 c# 6.0 进行编译?我必须要有 visual studio 吗?还有其他选择吗?

您可以使用 /r:

指定旧的 .NET 程序集
 /reference:<alias>=<file>     Reference metadata from the specified assembly
                               file using the given alias (Short form: /r)
 /reference:<file list>        Reference metadata from the specified assembly
                               files (Short form: /r)

您还需要使用 /nostdlib:

来抑制现代 mscorlib 的自动包含
 /nostdlib[+|-]                Do not reference standard library (mscorlib.dll)

总之,您可以使用 C# 6 编译器构建 .NET 2.0 应用程序。

csc.exe /r:"C:\Windows\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll" /nostdlib Program.cs

您甚至可以在您的应用中使用 C# 6 功能! (只要它们是不涉及 .NET 运行时的仅限编译器的功能)

public static string MyProp { get; } = "Hello!";
static void Main(string[] args)
{
    Console.WriteLine(MyProp);
    // prints "Hello!"

    var assembly = Assembly.GetAssembly(typeof(Program));
    Console.WriteLine(assembly.ImageRuntimeVersion);
    // prints "v2.0.50727"
}