Get Symbol for ReferenceLocation

夙愿已清 提交于 2020-01-01 12:15:10

问题


I'm using the SymbolFinder to find all references to a certain type in my solution like this:

ISymbol typeOfInterest = compilation.GetTypeByMetadataName(
    "System.Reflection.PropertyInfo");
var references = SymbolFinder.FindReferencesAsync(typeOfInterest, solution).Result;
foreach (var reference in references)
{
    // reference.Locations => symbol?
}

This part is working fine, the SymbolFinder returns correct ReferenceLocations (upon manual inspection). I'm actually interested in the symbols at these locations to get more (semantic) information about the references, so I can filter upon / work with it (e.g. only work on properties).

There seems to be very little public information on Roslyn yet and I couldn't find anything working with the results of SymbolFinder in the samples of the SDK Preview. So here is my question: Is it possible to get the symbol corresponding to a ReferenceLocation? How?


回答1:


So, there isn't strictly a "symbol" at any of these locations, at least no innate concept of that. What you can do is take that Location, and find the enclosing symbol. You can take the location's SyntaxTree and get a Document. From there, call GetSemanticModelAsync, and then call ISemanticModel.GetEnclosingSymbol.

As an example, here's some (internal) code that does this for FAR itself: https://github.com/dotnet/roslyn/blob/748d6ab1b504ceee0c29f132fdcbe2a777aa88ea/src/Workspaces/Core/Portable/FindSymbols/ReferenceLocationExtensions.cs#L67-L101



来源:https://stackoverflow.com/questions/22924043/get-symbol-for-referencelocation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!