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

2 c# compiler-errors record .net-5 c#-9.0

编辑:谢谢大家!我以前从未升级到较新版本的 .NET 和语言版本。因此不知道 .csproj 配置。尽管我在发布问题之前进行了研究,但我自己无法找到解决方案。因此,我只是留下这两个链接以供进一步参考,也许这也可能对某人有所帮助。

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

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

我已经升级到.NET 5 .0.301

终于抽出时间尝试C# 9 .0中的记录类型

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

我使用Visual Studio Code作为编辑器。

VS 代码版本1.57.0

C# 扩展版本1.23.12

这是我的settings.json

"editor.semanticHighlighting.enabled": true,
"csharp.semanticHighlighting.enabled": true,
"omnisharp.path": "latest"
Run Code Online (Sandbox Code Playgroud)

设置:

dotnet new sln -n "Test"
dotnet new console -n "TestProject"
dotnet sln Test.sln add  .\TestProject\TestProject.csproj
Run Code Online (Sandbox Code Playgroud)

我的代码:

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; }
    }

}
Run Code Online (Sandbox Code Playgroud)

问题:

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
Run Code Online (Sandbox Code Playgroud)

非常感谢任何帮助

Jos*_*lva 8

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

<TargetFramework>net5.0</TargetFramework>
<LangVersion>9.0</LangVersion>
Run Code Online (Sandbox Code Playgroud)

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

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