从 Roslyn 中的行号获取节点 [英] Getting node from line number in Roslyn

查看:47
本文介绍了从 Roslyn 中的行号获取节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何根据行号获取SyntaxNode?否则,如果有可能获得该行号的 LineSpan 然后到节点.

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.

推荐答案

您可以从文档文本中获取行的跨度.从那里,您可以找到与线跨度相交的所有节点.这将返回多个语法节点,然后您可以使用您的条件来提取您要查找的一个:

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

这篇关于从 Roslyn 中的行号获取节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆