Search for attributes in the base type

I am trying to implement ICodeIssueProvider to determine if a class (or one of its base types) has a specific attribute or not.

 public IEnumerable<CodeIssue> GetIssues(IDocument document, CommonSyntaxNode node, CancellationToken cancellationToken) { var methodDeclaration = (MethodDeclarationSyntax)node; var semanticModel = document.GetSemanticModel(cancellationToken); var methodSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration); var typeSymbol = methodSymbol.ContainingType; // The following only gets attributes declared on this class, how to // also include those declared on a base class ? var attributes = typeSymbol.GetAttributes(); 

Is there a better way than going up typeSymbol.BaseType all the way to System.Object and calling GetAttributes() along the way?

Also, is there a better way to check if typeSymbol is being typeSymbol from a specific class, than go up .BaseType and check manually

(And yes, there is a reason not obvious from the example below for checking MethodDeclarationSyntax nodes, not ClassDeclarationSyntax nodes)

+4
source share
1 answer

TL; DR; No, there is no single method call for this (as of September 2012 CTP Roslyn).

The parent classes to look for can be (and usually) a completely separate syntax tree for the class you are in. If all your classes were in the same namespace declaration (shudder), you could look for the root from this SyntaxNode .

Most likely, your classes are one for each file, so although they use the same namespace, they are not under the same root of the syntax tree.

Roslyn causes a lot of head scratches because the syntax trees are more like the location of the code files, rather than the types that the code represents.

Perhaps there is a way to create a new syntax tree (existing syntax trees are immutable) from all classes existing under this namsepace , and then search for this tree. For me, this seems more complicated than necessary, especially in the sense that the walking parent method is much more convenient to maintain.

+1
source

Source: https://habr.com/ru/post/1482249/


All Articles