How to Compile C# with Specific Language Version

柔情痞子 提交于 2019-11-27 17:26:57

问题


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


来源:https://stackoverflow.com/questions/29476057/how-to-compile-c-sharp-with-specific-language-version

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!