Roslyn: 是 ISymbol.GetAttributes returns 继承的属性

Roslyn: is ISymbol.GetAttributes returns inherited attributes

Roslyn 具有包含各种有用方法的 ISymbol 接口。我正在尝试通过 ISymbol.GetAttributes 获取所有 class 属性。这是一个文档 link:

https://docs.microsoft.com/de-de/dotnet/api/microsoft.codeanalysis.isymbol.getattributes?view=roslyn-dotnet

正如我们所见,没有任何迹象表明此方法 returns 是否继承了属性(来自基础 classes 的属性)。所以这是第一个问题。 第二个问题 - 为什么在文档中没有提及?

我不知道为什么文档中没有提到它,但我认为应该在那里提到它。

因为我遇到了同样的问题,所以我测试了一下,它不会return继承属性。您可以使用这些扩展方法来获取所有属性,包括继承的属性:

public static IEnumerable<AttributeData> GetAttributesWithInherited(this INamedTypeSymbol typeSymbol) {
    foreach (var attribute in typeSymbol.GetAttributes()) {
        yield return attribute;
    }

    var baseType = typeSymbol.BaseType;
    while (baseType != null) {
        foreach (var attribute in baseType.GetAttributes()) {
            if (IsInherited(attribute)) {
                yield return attribute;
            }
        }

        baseType = baseType.BaseType;
    }
}

private static bool IsInherited(this AttributeData attribute) {
    if (attribute.AttributeClass == null) {
        return false;
    }

    foreach (var attributeAttribute in attribute.AttributeClass.GetAttributes()) {
        var @class = attributeAttribute.AttributeClass;
        if (@class != null && @class.Name == nameof(AttributeUsageAttribute) &&
            @class.ContainingNamespace?.Name == "System") {
            foreach (var kvp in attributeAttribute.NamedArguments) {
                if (kvp.Key == nameof(AttributeUsageAttribute.Inherited)) {
                    return (bool) kvp.Value.Value!;
                }
            }

            // Default value of Inherited is true
            return true;
        }
    }

    return false;
}