我可以使用 <inheritdoc cref> 来引用另一个变量的 XML 摘要吗?

Can I use <inheritdoc cref> to reference the XML summary of another variable?

当我为我的项目编写函数时,更具体地说,他们的 XML 文档注释,我发现自己经常重复特定参数的注释。这有时会导致误导性文档(就像复制粘贴通常那样...)。

这是我想到的一个简单的例子,代表了真正的问题。

/// <summary>
/// The number that should be doubled
/// </summary>
private static float myNumber = 10f;

/// <summary>
/// Multiplies a number by 2
/// </summary>
/// <param name="number"><inheritdoc cref="myNumber"/></param>
/// <returns>The number multiplied by 2</returns>
private static float MultiplyByTwo(float number)
{
    return number * 2f;
}

在这一行 /// <param name="number"><inheritdoc cref="myNumber"/></param> 中,我想要文本“The number that should be doubled”,但它没有显示出来。可能是我没有完全理解inheritdoc的用法

我说的出现是这个意思。 Visual Studio 应在该框中显示 number 的文档:

它应该是这样的(没有复制粘贴文本):

那么,有没有办法在 XML 文档注释中引用不同的变量?

在 Visual Studio 16.8.4 中,我可以使用 <inheritdoc>path 属性来执行此操作。

/// <summary>
/// The number that should be doubled
/// </summary>
private static float myNumber = 10f;
        
/// <summary>
/// Multiplies a number by 2
/// </summary>
/// <param name="number"><inheritdoc cref="myNumber" path="/summary"/></param>
/// <returns></returns>
private static float MultiplyByTwo(float number)
{
    return number * 2f;
}

path 属性中,/ select 是 'root' 节点,然后 summary 是 select 的节点节点。

结果:

path 属性使用 XPath 语法,您可以 find more about here.

如果你小心的话,你可以用它来做一些很棒的事情;我在实施 Try[...] 模式时经常使用它。

例如:

/// <summary>
/// This throws!
/// </summary>
/// <param name="param1">This is a parameter.</param>
/// <param name="param2">This is another parameter!</param>
/// <exception cref="InvalidOperationException"/>
public string ExampleThatCanThrow(int param1, float param2)
{
    throw new InvalidOperationException();
}

/// <summary>
/// This never throws!
/// </summary>
/// <inheritdoc cref="ExampleThatCanThrow(int, float)" path="/*[not(self::exception)]"/>
public bool TryExample(int param1, float param2, out string? result)
{
    result = "No throwing here!";
    return true;
}

通常这样对TryExample方法使用<inheritdoc>时,会显示可以抛出InvalidOperationException。使用 path 属性,我对其进行了过滤,因此只有与 exception 名称不匹配的节点才会被继承。

/:匹配根节点。

*:匹配任意子节点。

[]:匹配任何满足包含谓词条件的节点。

not():匹配任何不满足括号内表达式条件的节点。

self::exception:如果当前节点的名称为exception,则匹配当前节点。

结果如下:

此外,您可以使用此功能更轻松地显示方法可能抛出的异常,而无需显式键入它们:

/// <summary>
/// Validates a file in some way.
/// </summary>
/// <param name="filePath">A full path to the file to be validated.</param>
/// <inheritdoc cref="File.OpenRead(string)" path="/exception"/>
private static void ValidateFile(string filePath)
{
    using FileStream file = File.OpenRead(filePath);
    // Validation code...
}

上面对 <inheritdoc> 的使用将导致方法的工具提示显示它可以抛出 System.IO.File.OpenRead 方法可以抛出的所有异常。请注意确保实际抛出并说明必要的验证异常。