How to Compile C# with Specific Language Version

2020-02-10 01:42发布

问题:

Let's say I want to demo to someone about the differences between foreach in C# 4.0 and 5.0.

So I write up my code snippet:

public static void Main()
{
    string[] fruits = { "Apple", "Banana", "Cantelope" };
    var actions = new List<Action>();
    foreach (var fruit in fruits)
    {
        actions.Add(() => Console.WriteLine(fruit));
    }

    foreach(var a in actions)
    {
        a();
    }   
}

But no matter how I compile it, it always works as it does in 5.0*. I've tried setting the language version in the csproj file (Build -> Advanced -> Language Version) and I've tried just building it on the command line:

csc myProgram.cs /langversion:4

I can't get it to work the "old" way. Any help? Bonus points if you can tell me how to do it on both the command line and Visual Studio.

* For anyone who doesn't know, in C#. <= 4.0 this would print Cantelope Cantelope Cantelope, while in C# 5.0+ it would (more intuitively) print Apple Banana Cantelope. Here's a link, and here's another.

回答1:

The purpose of the /langversion is only to make the compiler accept specific language constructs. It does not affect the actual behaviour of the compiler.

The documentation states that:

Causes the compiler to accept only syntax that is included in the chosen C# language specification.

and

Because each version of the C# compiler contains extensions to the language specification, /langversion does not give you the equivalent functionality of an earlier version of the compiler.

So to demonstrate the different behaviour, you will have to use a different csc.exe, installed with the right framework versions.

C:\Windows\Microsoft.NET\Framework\v3.5>csc /out:c:\temp\foo-35.exe c:\temp\foo.cs
Microsoft (R) Visual C# 2008 Compiler version 3.5.30729.7903
for Microsoft (R) .NET Framework version 3.5
Copyright (C) Microsoft Corporation. All rights reserved.


C:\Windows\Microsoft.NET\Framework\v3.5>c:\temp\foo-35.exe
Cantelope
Cantelope
Cantelope


标签: c# csc