Roslyn检查属性的类型

joh*_*y 5 1 c# linq roslyn

我试图找出在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?
}
Run Code Online (Sandbox Code Playgroud)

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

Mat*_*ren 6

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

var desiredSymbol = sematicModel.Compilation.GetTypeByMetadataName(typeof(MyAttributeType).FullName)
Run Code Online (Sandbox Code Playgroud)