为什么在 C# 中尝试使用记录类型时出现编译错误?

Why do I get compilation error when trying to use record type in C#?

EDIT: Thank you everyone! I have never upgraded to a newer version of .NET and language version before. Thus didn't know about .csproj configuration. Even though I did a research before posting a question I was not able to find a solution myself. So, I just leave these two links for further reference, perhaps this might help someone as well.

https://docs.microsoft.com/en-us/dotnet/standard/frameworks

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

我已经升级到.NET 5.0.301

终于抽出时间在 C# 9.0

中尝试 记录类型

我写了一个简单的代码,但是在编译过程中出现了错误。

我使用Visual Studio代码作为编辑器。

VS Code 版本 1.57.0

C#扩展版本1.23.12

这是我的settings.json:

"editor.semanticHighlighting.enabled": true,
"csharp.semanticHighlighting.enabled": true,
"omnisharp.path": "latest"

设置:

dotnet new sln -n "Test"
dotnet new console -n "TestProject"
dotnet sln Test.sln add  .\TestProject\TestProject.csproj

我的代码:

using System;

namespace TestProject
{

    class Program
    {
        static void Main(string[] args)
        {
            var person = new Person() { Name = "Tom" };
            person.Name = "Bob";
            Console.WriteLine(person.Name);
        }
    }

    public record Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

}

问题:

CS0246 The type or namespace name 'Person' could not be found (are you missing a using directive or an assembly reference?)
CS0246 The type or namespace name 'record' could not be found (are you missing a using directive or an assembly reference?)
CS0548 '<invalid-global-code>.Person': property or indexer must have at least one accessor
CS1513 } expected
CS0116 A namespace cannot directly contain members such as fields or methods
CS1022 Type or namespace definition, or end-of-file expected

非常感谢任何帮助

检查 .csproj 文件中的目标框架和语言版本。你应该找到类似的东西:

<TargetFramework>net5.0</TargetFramework>
<LangVersion>9.0</LangVersion>

如果您没有找到这些属性,请将它们添加到 <PropertyGroup>...</PropertyGroup> 标签内。如果它们设置为旧版本,请更改它们。

如果这不能解决您的问题,您可能未正确安装 .NET SDK,或者您可能已将其安装在默认目录以外的目录中,而 VS Code C# 扩展无法找到它。