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



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

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

如我们所见,没有指示此方法是否返回继承的属性(来自基类的属性(。所以这是第一个问题。第二个问题 - 为什么文档中没有提到这一点?

我不知道

为什么文档中没有提到它,并认为应该在那里提到它。

由于我面临同样的问题,我对其进行了测试,它不会返回继承的属性。可以使用这些扩展方法来获取所有属性,包括继承的属性:

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

最新更新