首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Roslyn确定行代码在源文件中的位置

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

Stack Overflow用户
提问于 2018-07-18 02:27:07
回答 1查看 1.7K关注 0票数 5

我做了一些关于堆叠溢出的研究,但是我找不到我需要的结果。我的问题是“如何使用Roslyn确定行代码对源文件的位置”。例如:我有一个源文件(名为: sample.cs),它的内容如下

代码语言:javascript
复制
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“(覆盖访问者方法)来实现它,但我不知道如何实现?如何知道代码"if (a >b&a&a/b>1&b-a == 1)",位置在源文件sample.cs中的24行?对这种情况有什么建议吗?谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-17 00:02:06

在@的注释上展开,您可以从其语法树中获得节点的行号:

代码语言:javascript
复制
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

票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51392704

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档