How to use C# to find usages of a class or method?

2019-01-14 17:45发布

问题:

In Visual Studio, I can right-click a class or method and choose "Find usages". That gives me a list of places in my solution where that piece of code is used. How can I do the same from my code?

回答1:

You would need to parse your code to do this. I don't think you could do it with reflection. MS have been working on a project called Roslyn. This is kind of an API for the .NET compiler. It should provide you with what you need. Check out this post for details of the Roslyn project.

Quote from the post:

This opens up new opportunities for VS extenders to write powerful refactorings and language analysis tools, as well as allow anyone to incorporate our parsers, semantic engines, code generators and scripting in their own applications.

This post demonstrates working with symbols.
This post answers the question of getting all references.



回答2:

To be honest, I never did that before, as I never needed kind of thing.

For access to kind of information you need to have access to Token Tree of the compiler, constructed for semantic analysis.

That kind of information, for sure you can have access from Roslyn (API for C# compiler). Where you can push into the API function a C# text, run a compiler over it and recover Tokens tree.

The Roslyn Project Overview

Hope this helps.



回答3:

As far as I know, there is no way to find all usages across all the projects in your solution. If your class has a unique name to it, Visual Studio's search function has an "Entire Solution" search scope, which looks for the exact search text in every file in your solution.

This doesn't specifically find every time your method is being used, as it also matches comments, similarly named fields, anything with the same string, but it's a good start.