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

时间:2016-04-06 21:54:36

标签: c# .net compilation visual-studio-2015 c#-6.0

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

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

那么如何编译CLR 2和c#6.0?我必须有视觉工作室吗?还有其他选择吗?

1 个答案:

答案 0 :(得分: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"
}