将常量渲染到XML文档中?

tse*_*mer 28 c# xml-documentation visual-studio

我有2个私有consts和一个公共方法:

private const byte _minAge = 24;
private const byte _maxAge = 29;

public bool IsInAgeRange() { ... }
Run Code Online (Sandbox Code Playgroud)

我正在添加XML文档,如果我的代码的用户可以在IntelliSense中读取它,我希望它是最好的: Checks whether the age is within the allowed range (between 24 and 29).

我的问题是:有没有办法将我的consts渲染到我的XML文档中?


我提出的替代方案是:

  1. 只需在文档中写入24和29(缺少对实际值的依赖)
  2. 使consts公开并添加<see cref="MinAge"><see cref="MaxAge">(减少封装并使文档信息量减少)

小智 6

为包含该值的每个常量添加摘要,然后参考这些注释:

/// <summary>24</summary>
private const byte _minAge = 24;
/// <summary>29</summary>
private const byte _maxAge = 29;

/// <summary>Checks whether the age is within the allowed range (between <inheritdoc cref="_minAge"/> and <inheritdoc cref="_maxAge"/>).</summary>
public bool IsInAgeRange() { ... }
Run Code Online (Sandbox Code Playgroud)

我知道它仍然是重复的,但是这样你可以将常量注释保持在常量附近,即使常量完全在另一个文件中定义。

  • @EricMutta当在标签内部使用“&lt;inheritdoc&gt;”并且仅使用cref但未指定路径值时,默认情况下“&lt;inheritdoc&gt;”将仅引用ref目标中的相同标签。因此,如果您在“&lt;param&gt;”标记内使用“&lt;inheritdoc&gt;”,则只会使用引用目标的同一“&lt;param&gt;”标记的内容。如果您想从`&lt;param&gt;`标记内部引用@kalu93的答案中的ref目标的摘要标记的内容,请使用`&lt;inheritdoc cref =“_minAge”path =“//summary”/&gt;` 。路径选项使用 XPath 表示法来选择引用的目标。 (4认同)
  • 对于尝试此操作的其他人,请注意它仅在“&lt;summary&gt;”标记内有效。我在“&lt;param&gt;”标签的文本中尝试了它,但它不起作用。此外,如果您使用 Swagger 来记录 ASP.NET Web API,则使用 `&lt;inheritdoc&gt;` 标记无法正常工作(XML 是逐字呈现的,而不是呈现实际继承的文档 - 请参阅此 [问题](https: //github.com/domaindrivendev/Swashbuckle.WebApi/issues/1000))。 (3认同)
  • 我建议使用“&lt;value&gt;”标签,而不是将数字放在“&lt;summary&gt;”标签内。它更具语义性,并为更相关的内容留下了“&lt;summary&gt;”标签。然后可以使用 `&lt;inheritdoc cref="_minAge" path="//value"/&gt;` 引用该值 (2认同)

nic*_*hev 5

我认为没有任何方法可以在文档中写入常量的实际值_minAge_maxAge但您可以使用标签引用它们,<see>如下所示:

/// <summary>
/// Checks whether the age is within the allowed range (between <see cref="_minAge" /> and <see cref="_maxAge" />).
/// </summary>
Run Code Online (Sandbox Code Playgroud)

现在,这将创建指向文档中这些常量的链接,以便当您生成文档并稍后呈现它们时,用户将能够单击这些链接并引用适当的常量。

  • 你似乎在重复我在替代方案#2中提到的内容;看到那里的缺点 (5认同)
  • 是的,我想这行不通。但是你可以问自己,为什么当“IsInAgeRange()”是公共的时,常量是私有的?为什么用户可以验证对象的年龄但不知道它被认为有效的条件? (3认同)

Eri*_*tta 5

<inheritdoc/>这结合了 @kalu93 的答案和 @DhyMik 的评论,以展示如何在<summary>标签和标签中使用<param>

    /// <summary>24</summary>
    private const byte _minAge = 24;
    /// <summary>29</summary>
    private const byte _maxAge = 29;

    /// <summary>
    /// Checks whether the age is within the allowed range 
    /// (between <inheritdoc cref="_minAge"/> and <inheritdoc cref="_maxAge"/>).
    /// </summary>
    /// <param name="TheAge">
    /// Age (must be between <inheritdoc cref="_minAge" path="//summary"/> and 
    /// <inheritdoc cref="_maxAge" path="//summary"/>).
    /// </param>
    public bool IsInAgeRange(int TheAge) { 
      return _minAge <= TheAge && TheAge <= _maxAge; 
    }
Run Code Online (Sandbox Code Playgroud)

现在,当您将鼠标悬停在函数上时,Visual Studio 可以正确显示限制IsInAgeRange

函数提示

...以及当您将鼠标悬停在参数上时TheAge

参数提示