简体   繁体   English

c#语言版本有指令吗

[英]Is there directive for c# language version

Is there any predefined constant to distinguish language versions, such as:有没有预定义的常量来区分语言版本,比如:

#if C#6
 //code
#else
 //code
#endif

You shouldn't have to do this.你不应该这样做。

Typically, you would do something like this to support different versions of .NET framework.通常,您会执行类似的操作来支持不同版本的 .NET 框架。 Not different versions of the C# compiler.不是不同版本的 C# 编译器。 Newer compiler can target older versions of the framework.较新的编译器可以针对较旧版本的框架。 In short, use the latest C# compiler features.简而言之,使用最新的 C# 编译器功能。 The compiler is free, so there isn't any real roadblock to updating a project to use the latest features.编译器是免费的,因此更新项目以使用最新功能没有任何真正的障碍。

Depending on your environment you can rely on the platform version or not.根据您的环境,您可以依赖或不依赖平台版本。 If the projects do not use custom explicit language versions, you can try to use the target framework directives.如果项目不使用自定义显式语言版本,您可以尝试使用目标框架指令。

编译器根据以下规则确定默认值: https://learn.microsoft.com/en-us/do.net/csharp/language-reference/configure-language-version#defaults https://learn.microsoft.com/en-us/do.net/csharp/language-reference/configure-language-version#defaults

.NET Framework
NETFRAMEWORK, NET48, NET472, NET471, NET47, NET462, NET461, NET46, NET452, NET451, NET45, NET40, NET35, NET20

.NET Standard
NETSTANDARD, NETSTANDARD2_1, NETSTANDARD2_0, NETSTANDARD1_6, NETSTANDARD1_5, NETSTANDARD1_4, NETSTANDARD1_3, NETSTANDARD1_2, NETSTANDARD1_1, NETSTANDARD1_0

.NET 5+ and .NET Core
NET, NET6_0, NET6_0_ANDROID, NET6_0_IOS, NET6_0_MACOS, NET6_0_MACCATALYST, NET6_0_TVOS, NET6_0_WINDOWS, NET5_0, NETCOREAPP, NETCOREAPP3_1, NETCOREAPP3_0, NETCOREAPP2_2, NETCOREAPP2_1, NETCOREAPP2_0, NETCOREAPP1_1, NETCOREAPP1_0

https://stackoverflow.com/questions/38476796/how-to-set.net-core-in-if-statement-for-compilation https://stackoverflow.com/questions/38476796/how-to-set.net-core-in-if-statement-for-compilation

So you can use if-else directives with these keywords所以你可以使用带有这些关键字的 if-else 指令

#if NET5_0
// GG C# 9
#endif

There are also other directive keywords with the higher or lower keyword还有其他带有higherlower关键字的指令关键字

#if NET5_0_OR_GREATER  // up-level version
#else  // down-level version
#endif

This approach is unreliable if you actually need only language version specific features.如果您实际上只需要特定于语言版本的功能,则此方法不可靠 I recommend to set the latest language version in your csproj.我建议在您的 csproj 中设置最新的语言版本。

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

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