简体   繁体   English

如何使用特定语言版本编译 C#

[英]How to Compile C# with Specific Language Version

Let's say I want to demo to someone about the differences between foreach in C# 4.0 and 5.0.假设我想向某人演示 C# 4.0 和 5.0 中 foreach 之间的差异。

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 * .但无论我如何编译它,它总是像在 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:我试过在 csproj 文件(构建 -> 高级 -> 语言版本)中设置语言版本,我试过在命令行上构建它:

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.如果您能告诉我如何在命令行和 Visual Studio 上执行此操作,则可以加分。

* For anyone who doesn't know, in C#. * 对于不知道的人,在 C# 中。 <= 4.0 this would print Cantelope Cantelope Cantelope , while in C# 5.0+ it would (more intuitively) print Apple Banana Cantelope . <= 4.0 这将打印Cantelope Cantelope Cantelope ,而在 C# 5.0+ 中它会(更直观地)打印Apple Banana Cantelope Here's a link , and here's another . 这是一个链接这是另一个

The purpose of the /langversion is only to make the compiler accept specific language constructs. /langversion的目的只是让编译器接受特定的语言结构。 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.使编译器仅接受所选 C# 语言规范中包含的语法。

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.因为 C# 编译器的每个版本都包含语言规范的扩展,所以 /langversion 不会为您提供与早期版本的编译器等效的功能。

So to demonstrate the different behaviour, you will have to use a different csc.exe, installed with the right framework versions.因此,为了演示不同的行为,您必须使用不同的 csc.exe,并安装了正确的框架版本。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM