如何向 C# 9 记录添加注释

Muh*_*eed 5 c# comments record c#-9.0

C# 9 记录有一个简短的形式,如下所示:

public record Car(int CarId, int Cylinders, string Make, string Model);
Run Code Online (Sandbox Code Playgroud)

如何将文档注释添加到记录的属性中?请注意,这是不同的这一哪个询问长形式等问题。

Sim*_*tes 10

正确的方法看起来就像这样简单:

/// <summary>
/// Represents a car.
/// </summary>
/// <param name="CarId">The id of the car.</param>
/// <param name="Cylinders">The number of cylinders.</param>
/// <param name="Make">The make of the car.</param>
/// <param name="Model">The model of the car.</param>
public record Car(int CarId, int Cylinders, string Make, string Model);
Run Code Online (Sandbox Code Playgroud)

当您创建此记录的新实例时,这在 IDE 的 IntelliSense(在 VSCode 上进行测试)中确实有效(即new Car(...)会为您提供不同参数的信息)。

但是,如果您<GenerateDocumentationFile>true</GenerateDocumentationFile>.csproj. 对于每个参数,您将获得以下警告对:

warning CS1572: XML comment has a param tag for 'CarId', but there is no parameter by that name
warning CS1573: Parameter 'CarId' has no matching param tag in the XML comment for 'Car.Car(int, int, string, string)' (but other parameters do)
Run Code Online (Sandbox Code Playgroud)

所以它确实有效,但是编译器抱怨参数没有被记录,并且有一个不存在的参数的文档。

将记录参数放在 xml docs 的范围内 #49134可能会在下一个版本中解决这个问题,希望如此。

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