如何创建 C# 8.0 控制台应用程序?

How do I create a C# 8.0 Console application?

我尝试通过模板创建 Windows Forms .NET core 3.1 应用程序并将输出类型切换为控制台应用程序。

这是我的代码:

static class Program
{
    static void Main()
    {
        System.Console.WriteLine(0 switch { 0 => "Hello World" });
    }
}

编译时得到:

error CS8370: Feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater.

我的目标是 .NET Core 3.1。我认为默认情况下会为我提供 C# 8.0 语言功能。看来我错了。

我该怎么办?

编辑: 我正在使用 Visual Studio 2019 16.3.9

这是最让我困惑的部分,因为它说语言版本是 "Automatically selected based on framework version"(我无法更改它。)而且我没有看到关于为什么我可以的充分解释不要在 Why can't I select a different C# version? 更改语言版本 该页面说如果我使用 .NET Core 3.x 我应该使用 C# 8.0。

.csproj文件如下:

<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <UseWindowsForms>true</UseWindowsForms>
    <ApplicationIcon />
    <StartupObject>Program</StartupObject>
  </PropertyGroup>

</Project>

添加此行可解决问题:

    <LangVersion>8.0</LangVersion>

但这真的是创建应用程序的唯一方法吗?我必须手动编辑我的 .csproj?为什么我不能更改语言版本,为什么它不会根据我使用 .NET Core 3.1 自动选择 C# 8.0?

打开你的csproj,看看你是否有像

这样的行
    <LangVersion>7.3</LangVersion>

如果是,请尝试删除它,如果不起作用,请尝试将其更改为 8.0

来自https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/configure-language-version#defaults

You should remove the <LangVersion>latest</LangVersion> from your project file when you update the .NET SDK.

我遇到了同样的问题(c#8 在 Core 3.1 项目上不可用),然后我就这样解决了:

  1. 卸载以前版本的 Visual studio(我的 2015 和 2017 例)
  2. 修复 Visual studio 2019(在我的例子中是 V16.4.1)"visual studio installer" 以管理员权限启动。

csproj 中不需要 LangVersion。