How to check if a property is decorated with a custom attribute using Roslyn?

孤街醉人 提交于 2019-12-12 11:06:48

问题


I want to analyse a C# class using Roslyn and intend to do something when visited property has the specific attribute applied to it. How can I do this in the CSharpSyntaxWalker.VisitPropertyDeclaration method override?

For example, in the following code block I want to know whether the Date property has the Validation attribute or not, and if so, whether IsJDate is true or false?

[Validation(IsJDate=true)]
public string Date {get; set;}

Initializations:

filesPath.ToList().ForEach(csFilePath =>
{
    SyntaxTree csSyntaxTree = CSharpSyntaxTree.ParseText(csFileSourceCode);
    // ....
}
_compiledCsCodes = CSharpCompilation.Create("CSClassesAssembly", csFiles.Select(cs => cs.CSSyntaxTree ), references);
foreach (CsFile csFile in csFiles)
{
     csFile.FileSemanticModel = _compiledCsCodes.GetSemanticModel(csFile.FullSyntaxTree);
}

回答1:


Finally, I found the solution by making some changes to Yuriy's answer as following:

foreach (var attribute in node.AttributeLists.SelectMany(al => al.Attributes))
{
    if (csFile.FileSemanticModel.GetTypeInfo(attribute).Type.ToDisplayString() == "Proj.Attributes.ValidationAttribute")
    {
        var arg = attribute.ArgumentList.Arguments.FirstOrDefault(aa => aa.NameEquals.Name.Identifier.Text == "IsJDate");
        if (arg != null && arg.Expression.IsKind(SyntaxKind.TrueLiteralExpression))
            validationKind = ValidationKind.JDate;
    }
}



回答2:


Use the semantic model to get the bound ISymbol for the property, then call GetAttributes().



来源:https://stackoverflow.com/questions/27601687/how-to-check-if-a-property-is-decorated-with-a-custom-attribute-using-roslyn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!