简体   繁体   中英

Roslyn - How can I get all references of a variable at DiagnosticAnalyzer class?

I'm currently trying to define a code fix with Roslyn. I have a SyntaxNode variable.

I would like to find all references of that variable at my DiagnosticAnalyzer class. Unfortunately SymbolFinder.FindReferencesAsync method requires a Solution parameter, and if I know well, I can't get the current solution from DiagnosticAnalyzer class.

How can I get all references of a variable at DiagnosticAnalyzer class?

I implemented a similar Analyzer, the algorithm was the following (it ran for ~31ms on a 2000+ line Document, but almost always under 10 ms)

  1. Iterate through all nodes in SemanticModel.GetRoot() and collect Expressions and LocalDeclarations
  2. Get the symbol of the corresponding Identifier
  3. Check if it implements IDisposable , store in HashSet1 if it does
  4. Iterate through Invocations where the method invoked is Dispose
  5. Get the symbol from Invocation, store in HashSet2
  6. Report Diagnostic on the first SyntaxReference of Symbols that are in HashSet1 but not in HashSet2

This works well, but sadly I do not know if there is a more efficient / cleaner way of doing this. I can share parts of the code if you like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM