Roslyn:ISymbol.GetAttributes是否返回继承的属性

5
1个回答

4

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

由于我遇到了相同的问题,所以我进行了测试,发现它将 不返回继承属性。您可以使用这些扩展方法获取所有属性,包括继承的属性:

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;
}

这个建议编辑建议将最后一行改为return true。我不知道这是否正确,但或许你可以看一下,确认一下是否正确? - undefined
@RyanM 建议的编辑是正确的。没有 AttributeUsage 属性的 Attribute 也会默认为可继承。谢谢你提到这个问题,以便修复。请参考 https://sharplab.io/#gist:68b6fa5f544509ce0403ea142951e8b5 查看测试案例。 - undefined

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