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

4
Visual Studio 2015没有问题使用新的C#编译器编译旧的CLR。看起来它在幕后使用VBCSCompiler.exe,但我找不到任何关于VBCSCompiler.exe命令行选项的文档。
另一方面,csc.exe似乎没有选择目标CLR的选项。您可以使用最新的csc.exe编译CLR 4,或者您可以使用旧的csc.exe编译CLR 2,但这样就不能使用C# 6.0。
那么我该如何编译CLR 2和C# 6.0?我需要Visual Studio吗?还有其他选项吗?

我将只是加上必要的警告注释,即2.0已不再受支持。 - Panagiotis Kanavos
1个回答

6

您可以使用/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"
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接