[英]Roslyn SymbolFinder Convert Location to Syntax Node
I'm using a SymbolFinder to find all references to a variable.我正在使用 SymbolFinder 来查找对变量的所有引用。 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
您可以使用接受TextSpan
FindNode()
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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.