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

后端 未结 1 1411
轮回少年
轮回少年 2021-01-20 14:05

Visual Studio 2015 has no problem compiling for the older CLR with new c# compiler. It seems that it uses VBCSCompiler.exe for this under the hood, but I cannot find any doc

相关标签:
1条回答
  • 2021-01-20 14:25

    You can specify old .NET assemblies with /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)
    

    You will also need to suppress the automatic inclusion of the modern mscorlib with /nostdlib:

     /nostdlib[+|-]                Do not reference standard library (mscorlib.dll)
    

    Together, these make it so that you can build .NET 2.0 apps with the C# 6 compiler.

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

    You can even use C# 6 features in your app! (as long as they are compiler-only features that don't involve the .NET runtime)

    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"
    }
    
    0 讨论(0)
提交回复
热议问题