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"))))
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With