在SyntaxTree中获取给定linenumber的SyntaxNode

我想得到给定位置(lineNumber)的一行的SyntaxNode。 下面的代码应该是不言自明的,但让我知道任何问题。

static void Main() { string codeSnippet = @"using System; class Program { static void Main(string[] args) { Console.WriteLine(""Hello, World!""); } }"; SyntaxTree tree = SyntaxTree.ParseCompilationUnit(codeSnippet); string[] lines = codeSnippet.Split('\n'); SyntaxNode node = GetNode(tree, 6); //How?? } static SyntaxNode GetNode(SyntaxTree tree,int lineNumber) { throw new NotImplementedException(); // *** What I did *** //Calculted length from using System... to Main(string[] args) and named it (totalSpan) //Calculated length of the line(lineNumber) Console.Writeline("Helllo...."); and named it (lineSpan) //Created a textspan : TextSpan span = new TextSpan(totalSpan, lineSpan); //Was able to get back the text of the line : tree.GetLocation(span); //But how to get the SyntaxNode corresponding to that line?? } 

首先,要根据行号获取TextSpan ,可以使用GetText()返回的SourceTextLines的索引器(但要小心,它会计算0行)。

然后,要获取与该跨度相交的所有节点,可以使用DescendantNodes()的重载。

最后,您筛选该列表以获取该行中完全包含的第一个节点。

在代码中:

 static SyntaxNode GetNode(SyntaxTree tree, int lineNumber) { var lineSpan = tree.GetText().Lines[lineNumber - 1].Span; return tree.GetRoot().DescendantNodes(lineSpan) .First(n => lineSpan.Contains(n.Span)); } 

如果该行上没有节点,则会抛出exception。 如果有多个,它将​​返回第一个。