如何在C# 9记录中添加注释

9

C# 9 的 record 类型有以下简写形式:

public record Car(int CarId, int Cylinders, string Make, string Model);

如何给记录的属性添加文档注释?请注意,这与其他问题中询问的长格式不同。

1个回答

20

正确的方法似乎就是这么简单:

/// <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);

当您创建这个记录的新实例时(例如,new Car(...)),它确实可以在IDE的IntelliSense中正常工作,并提供不同参数的信息。

然而,如果您在.csproj中启用了<GenerateDocumentationFile>true</GenerateDocumentationFile>,则编译器的警告系统似乎存在问题。对于每个参数,您将收到以下警告对:

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)

它确实有效,但编译器既抱怨参数未被记录,又有一个不存在的参数的文档。

将记录参数放入xml文档的范围中#49134或许会在下一个版本中修复这个问题。


3
供他人参考,此错误已在发布于2021年3月2日的.NET 5.0.200 SDK中得到解决。 - Matt Johnson-Pint
Intellisense(开始输入“param”)以及在记录上方添加3个斜杠(就像在类上方一样)后自动填充所有参数,在更新的VS2019中仍然无法正常工作,截至2021年9月。 - dudeNumber4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接