如何使用Roslyn确定行代码在源文件中的位置

时间:2018-07-18 02:27:08

标签: roslyn-code-analysis

我对stackoverflow进行了一些研究,但找不到所需的结果。 我的问题是“如何使用Roslyn确定源代码的行代码位置”。 例如:我有一个源文件(名为:sample.cs),内容看起来像

using System;

/// <summary>
/// This is summary of namespace
/// </summary>
namespace LearnRoslyn
{
    /// <summary>
    /// This is summary of class
    /// </summary>
    public class CodeSample2
    {

        public SampleClass MyMethod1(int a, int b, SampleClass cls)
        {
            //This is call method
            cls = new SampleClass();
            cls.MyMethod4(a);

            //This is 3-tier condition
            a = (a > b ? 1 : 0);

            //This is IF comment
            if (a > b && a / b > 1 && b - a == 1)
            {
                //This is another IF comment
                if (a > b || (a / b > 1 && b - a == 1))
                {
                    Console.WriteLine("a > b");
                }
            }
            else
            {
                if (cls != null)
                {
                    Console.WriteLine("a < b");
                }

                if (cls.IsNull)
                {
                    Console.WriteLine("a < b");
                }
            }

            return null;
        }

        public void MyMethod2(int n)
        {

            n = 2;
        }
    }

    public class SampleClass
    {
        public bool IsNull { get; set; }
        public void MyMethod3(int a, int b)
        {

            if (a > b)
            {
                Console.WriteLine("a > b");
            }
            else
            {
                Console.WriteLine("a < b");
            }
        }

        public void MyMethod4(int n)
        {

            n = 2;
        }
    }
}

据我所知,可以使用“ CSharpSyntaxWalker”(重写Visitor方法)来实现,但是我不知道怎么做? 如何知道代码“ 如果(a> b && a / b> 1 && b-a == 1)”,位于源文件 24 行> sample.cs ? 对这种情况有什么建议吗? 谢谢。

1 个答案:

答案 0 :(得分:1)

扩展@George Alexandria的注释,您可以从其语法树中获取节点的行号:

class MyWalker : CSharpSyntaxWalker
{
    public override void Visit(SyntaxNode node)
    {
        FileLinePositionSpan span = node.SyntaxTree.GetLineSpan(node.Span);
        int lineNumber = span.StartLinePosition.Line;

        // Do stuff with lineNumber.
        // ...
    }

    // ...
}

请参见SyntaxTree.GetLineSpan