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

问题描述 投票:0回答:2

编辑:谢谢大家!我从未升级到更新版本 .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 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

非常感谢任何帮助

c# compiler-errors record .net-5 c#-9.0
2个回答
6
投票

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

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

如果您没有找到这些属性,请将它们添加到

<PropertyGroup>...</PropertyGroup>
标签中。如果它们设置为旧版本,请更改它们。

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


0
投票

我认为你可以更改此代码:

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

这个:

public record Person(string Name, int Age )
© www.soinside.com 2019 - 2024. All rights reserved.