Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
457 views
in Technique[技术] by (71.8m points)

csc - 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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:WindowsMicrosoft.NETFrameworkv3.5>csc /out:c:empfoo-35.exe c:empfoo.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:WindowsMicrosoft.NETFrameworkv3.5>c:empfoo-35.exe
Cantelope
Cantelope
Cantelope

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...