Getting node from line number in Roslyn

送分小仙女□ 提交于 2019-12-04 07:54:12

You can get the span of a line from the document text. From there, you can find all nodes that intersect with the span of the line. This will return multiple syntax nodes, which you can then use your criteria to pull out the one you are looking for:

    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();
    }
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);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!