gpt4 book ai didi

roslyn-code-analysis - 如何使用 Roslyn 确定源文件中的行代码位置

转载 作者:行者123 更新时间:2023-12-03 18:45:35 27 4
gpt4 key购买 nike

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

最佳答案

扩展@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 .

关于roslyn-code-analysis - 如何使用 Roslyn 确定源文件中的行代码位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51392704/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com