Roslyn 检查属性的类型

Roslyn Check Type of an Attribute

我正在尝试找出在 Roslyn 中比较属性数据的正确方法。

static bool ResolveAttributes(IMethodSymbol methodSymbol)
{
    var attributes = methodSymbol.GetAttributes();

    return null == attributes.FirstOrDefault(attr => isIDEMessageAttribute(attr, typeof(MyAttributeType)));
}

static bool IsIDEMessageAttribute(AttributeData attribute, Type desiredAttributeType)
{
    //How can I check if the attribute is the type of desired?
}

如何检查属性是否是所需的类型?

AttributeData.AttributeClass 为您提供该属性的 Roslyn 符号。但是您有一个 CLR 运行时类型,您正试图与之进行比较。您可以只比较类型名称等,看看它们是否可能是同一类型,或者获取 MyAttributeType 的 Roslyn 类型符号,这更正确。这通常是通过

var desiredSymbol = sematicModel.Compilation.GetTypeByMetadataName(typeof(MyAttributeType).FullName)