这可能是由于编译器在不同的目标框架中默认使用不同版本的C#语言所致。
要覆盖默认的C#语言版本,请按照问题建议,向项目文件中添加:
<PropertyGroup>
<LangVersion>8.0</LangVersion>
</PropertyGroup>
或者:
<PropertyGroup>
<LangVersion>latest</LangVersion>
</PropertyGroup>
注意:不建议使用比默认版本更新的语言版本。
来自C# 语言版本控制 - Microsoft Docs(截至2022年03月11日):
这个默认选择还可以确保您不会使用需要目标框架中不可用的类型或运行时行为的语言。选择比默认版本更新的语言版本可能会导致难以诊断的编译时和运行时错误。
请参阅Microsoft Docs的C#语言版本控制,了解不同目标框架的默认C#语言版本以及如何手动选择C#语言版本。
此外,请参阅堆栈溢出答案C# 8是否支持.NET Framework?,以获取有关此主题的更多信息。
以下是关于不同目标框架的默认语言版本的
C#语言版本控制-Microsoft Docs文章的一部分(截至2022年03月11日):
C# language versioning
The latest C# compiler determines a default language version based on your project's target framework or frameworks. Visual Studio doesn't provide a UI to change the value, but you can change it by editing the csproj file. The choice of default ensures that you use the latest language version compatible with your target framework. You benefit from access to the latest language features compatible with your project's target. This default choice also ensures you don't use a language that requires types or runtime behavior not available in your target framework. Choosing a language version newer than the default can cause hard to diagnose compile-time and runtime errors.
C# 10 is supported only on .NET 6 and newer versions. C# 9 is supported only on .NET 5 and newer versions. C# 8.0 is supported only on .NET Core 3.x and newer versions.
...
Defaults
The compiler determines a default based on these rules:
╔══════════════════╦═════════╦═════════════════════════════╗
║ Target framework ║ version ║ C# language version default ║
╠══════════════════╬═════════╬═════════════════════════════╣
║ .NET ║ 6.x ║ C# 10 ║
║ .NET ║ 5.x ║ C# 9.0 ║
║ .NET Core ║ 3.x ║ C# 8.0 ║
║ .NET Core ║ 2.x ║ C# 7.3 ║
║ .NET Standard ║ 2.1 ║ C# 8.0 ║
║ .NET Standard ║ 2.0 ║ C# 7.3 ║
║ .NET Standard ║ 1.x ║ C# 7.3 ║
║ .NET Framework ║ all ║ C# 7.3 ║
╚══════════════════╩═════════╩═════════════════════════════╝
.NET Framework 4.6.1
, 且LangVersion
未设置。 - Ogglas