Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all properties that are anotated with some attribute?

Tags:

c#

roslyn

I am just starting with Roslyn, and I want to find all properties that are annotated with attribute names "OneToOne". I fired up SyntaxVisualizer and was able to get reference to that node, but I am wondering is there a simpler way to achieve this. This is what I have:

var prop = document.GetSyntaxRoot()
             .DescendantNodes()
             .OfType<PropertyDeclarationSyntax>()
             .Where(p => p.DescendantNodes()
                 .OfType<AttributeSyntax>()
                 .Any(a => a.DescendantNodes()
                     .OfType<IdentifierNameSyntax>()
                     .Any(i => i.DescendantTokens()
                         .Any(dt => dt.Kind == SyntaxKind.IdentifierToken
                                 && dt.ValueText == "OneToOne"))))
like image 901
epitka Avatar asked Dec 26 '22 18:12

epitka


1 Answers

Well, I would go about this using Semantics, not Syntax. Something like (off the top of my head):

var attributeSymbol = compilation.GetTypeByMetadataName("ConsoleApplication1.OneToOneAttribute");
var propertySymbol = compilation.GetTypeByMetadataName("ConsoleApplication1.Program")
                     .GetMembers()
                     .Where(m => 
                            m.Kind == CommonSymbolKind.Property && 
                            m.GetAttributes().Any(a => a.AttributeClass.MetadataName == attributeSymbol.MetadataName));
like image 191
Kevin Pilch Avatar answered May 12 '23 22:05

Kevin Pilch