我可以在构造函数注释中引用属性注释吗

本文关键字:注释 属性 引用 构造函数 我可以 | 更新日期: 2023-09-27 18:26:13

如果我的类有一个注释的公共属性,它是通过构造函数分配的,我可以从同名构造函数参数的描述中引用它的描述吗?

public class MyClass
{
    /// <summary>
    /// x description
    /// </summary>
    public int x { get; private set; }
    /// <summary>
    /// y description
    /// </summary>
    public int y { get; private set; }
    /// <summary>
    /// Constructor description
    /// </summary>
    /// <param name="x">How do I reference x description from here?</param>
    /// <param name="y">And y description?</param>
    public MyClass(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}

我可以在构造函数注释中引用属性注释吗

您不能包含描述,但可以使用<see>标记链接到属性文档。例如:

<param name="x">The initial value for <see cref="x"/></param>

顺便说一句,我强烈建议您遵循.NET命名约定,即公共成员以大写字母开头。

使用<inheritdoc/>可以实现这一点,特别是通过使用可选的crefpath属性。

注意:我不确定这是什么语言或框架版本,它适用于我使用的.NET5/C#9。如果有人用我可以编辑的起始版本发表评论。

参考:https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/xmldoc/recommended-tags#inheritdoc

对于您的示例(不同之处在于构造函数XML注释上的param元素):

public class MyClass
{
    /// <summary>
    /// x description
    /// </summary>
    public int x { get; private set; }
    /// <summary>
    /// y description
    /// </summary>
    public int y { get; private set; }
    /// <summary>
    /// Constructor description
    /// </summary>
    /// <param name="x"><inheritdoc cref="x" path='/summary'/></param>
    /// <param name="y"><inheritdoc cref="y" path='/summary'/></param>
    public MyClass(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}

这将使构造函数参数继承参数的摘要注释,从而减少冗余。