Getting node from line number in Roslyn

前端 未结 2 561
忘掉有多难
忘掉有多难 2021-02-15 15:43

How can I get a SyntaxNode based on a line number? Else if its possible to get LineSpan of that line number then to node.

2条回答
  •  深忆病人
    2021-02-15 16:20

    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);
    

提交回复
热议问题