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

And*_*ykh 3 .net c# compilation c#-6.0 visual-studio-2015

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

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

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

Tim*_* S. 6

您可以指定旧的.NET程序集/r:

 /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)
Run Code Online (Sandbox Code Playgroud)

您还需要禁止自动包含现代mscorlib /nostdlib:

 /nostdlib[+|-]                Do not reference standard library (mscorlib.dll)
Run Code Online (Sandbox Code Playgroud)

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

csc.exe /r:"C:\Windows\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll" /nostdlib Program.cs
Run Code Online (Sandbox Code Playgroud)

您甚至可以在应用中使用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"
}
Run Code Online (Sandbox Code Playgroud)