如何根据行号获得SyntaxNode
?否则,如果它可以获得该行号的LineSpan
,那么就到节点。
答案 0 :(得分:6)
您可以从文档文本中获取一行的范围。从那里,您可以找到与线的跨度相交的所有节点。这将返回多个语法节点,然后您可以使用您的条件来提取您要查找的节点:
static void Main(string[] args)
{
var code = @"
using System;
namespace ConsoleApplication1
{
class TypeName
{
public int Add(int x, int y)
{
return x+y;
}
}
}";
var st = SourceText.From(code);
var sf = SyntaxFactory.ParseSyntaxTree(st);
var span = sf.GetText().Lines[9].Span;
var nodes = sf.GetRoot().DescendantNodes().Where(x => x.Span.IntersectsWith(span));
Console.WriteLine(nodes.Last().ToString());
Console.ReadKey();
}
答案 1 :(得分:2)
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Text;
var s = @"class M
{
public void P() { }
}";
var text = SourceText.From(s);
var lineIndex = 2;
var lineSpan = text.Lines[lineIndex].Span;
var tree = SyntaxFactory.ParseSyntaxTree(text);
var node = tree.GetRoot().FindNode(lineSpan);
// or if you want a all nodes related to the span
var node = tree.GetRoot().DescendantNodesAndSelf(lineSpan);