2017-05-24 40 views
2

我正在使用SymbolFinder來查找對變量的所有引用。我想檢查這個字段是否被分配到它的定義之外。Roslyn SymbolFinder將位置轉換爲語法節點

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?    
} 

如何將位置轉換爲語法節點,然後檢查節點是否爲賦值?

回答

3

您可以使用FindNode()它接受一個TextSpan

所以,你的例子看起來是這樣的:

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

我創建了一個擴展方法,這樣做:

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)); 
} 
+0

我想你也可以使用:'location.SourceTree.GetRoot()。FindNode(location.SourceSpan)' – JoshVarty

+0

@JoshVarty我一直在挖掘博客的人,謝謝你是對的,與參考地點的位置。如果你把答案放在答案中,我會標記你的答案是正確的 –