简体   繁体   中英

Roslyn SymbolFinder Convert Location to Syntax Node

I'm using a SymbolFinder to find all references to a variable. I would like to check if this Field is assigned to outside of its definition.

var references = await SymbolFinder.FindReferencesAsync(equivalentSymbol, 
                              context.GetSolution(), cancellationToken);
//Reference is grouped by variable name 
var reference = references.FirstOrDefault();

foreach (var location in reference.Locations)
{
   //How Do I check if the reference is an assignment?               
}

How can I Convert the location into a syntax node, and then check if the node is an assignment?

You can use FindNode() which accepts a TextSpan

So your example would look something like:

var node = location.SourceTree.GetRoot().FindNode(location.SourceSpan);

I've created an extension Method to do so:

public static SyntaxNode GetNodeFromLocation(this SyntaxTree tree, ReferenceLocation location)
{ 
    var lineSpan = location.Location.GetLineSpan();
    return tree.GetRoot().DescendantNodes().FirstOrDefault(n => n.GetLocation().GetLineSpan().IsEqual(lineSpan));
}

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