使用 C#9 记录添加注释的正确方法是什么?

Xav*_*ohn 15 c#-9.0

在启用 Nullable 的情况下使用 C# 9 记录添加注释的正确方法是什么?

如果我尝试

public record Person
{
    /// <summary>
    /// Gets the first name.
    /// </summary>
    public string FirstName { get; init; }

    /// <summary>
    ///  Gets the last name.
    /// </summary>
    public string LastName { get; init; }
}
Run Code Online (Sandbox Code Playgroud)

我收到警告。

Non-nullable property 'FirstName' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.
Run Code Online (Sandbox Code Playgroud)

如果我尝试

public record Person(string firstName, string lastName);
Run Code Online (Sandbox Code Playgroud)

我收到警告。

Missing XML comment for publicly visible type or member 'Person.firstName'
Run Code Online (Sandbox Code Playgroud)

这也不起作用。

/// <summary>
/// Person.
/// </summary>
/// <param name="FirstName">Get the first name.</param>
/// <param name="LastName">Get the last name.</param>
public record Person(string FirstName, string LastName);
Run Code Online (Sandbox Code Playgroud)

发出警告。

XML comment has a param tag for 'FirstName', but there is no parameter by that name
Run Code Online (Sandbox Code Playgroud)

You*_*f13 8

对于第一种情况,您收到的警告与文档注释无关。您有一个不可为空的属性,其默认值等于null。这就是为什么你会收到警告。

对于第二种情况,这是编译器中的一个已知问题,正在dotnet/roslyn#49134 中修复

根据@matt-johnson-pint 评论进行编辑,此问题已通过 Visual Studio 16.9 和 .NET 5.0.200 SDK 修复

  • 仅供参考,该错误已在 2021 年 3 月 2 日发布的 .NET 5.0.200 SDK 中解决 (3认同)