gpt4 book ai didi

c# - 检测 C# 代码中的递归调用

转载 作者:IT王子 更新时间:2023-10-29 04:38:59 28 4
gpt4 key购买 nike

我想在我的代码中找到所有递归调用。

如果我在 Visual Studio 中打开文件,我会在编辑器左侧看到“递归调用”图标。 enter image description here

我想检查此类调用的整个解决方案。

我使用了 Resharper 命令行工具和 VS 的插件 Resharper - Code Inspection 但没有成功,这个规则没有应用在他们的规则集中。

有什么方法可以检查整个解决方案 - 我真的不想打开每个文件并检查那个蓝色的“递归调用”图标:)

编辑:我对单级递归感兴趣

最佳答案

可以Mono.Cecil来做.

这是一个简单的 LINQPad演示的程序:

const string AssemblyFilePath = @"path\to\assembly.dll";

void Main()
{
var assembly = ModuleDefinition.ReadModule(AssemblyFilePath);
var calls =
(from type in assembly.Types
from caller in type.Methods
where caller != null && caller.Body != null
from instruction in caller.Body.Instructions
where instruction.OpCode == OpCodes.Call
let callee = instruction.Operand as MethodReference
select new { type, caller, callee }).Distinct();

var directRecursiveCalls =
from call in calls
where call.callee == call.caller
select call.caller;

foreach (var method in directRecursiveCalls)
Debug.WriteLine(method.DeclaringType.Namespace + "." + method.DeclaringType.Name + "." + method.Name + " calls itself");
}

这将输出直接调用自身的方法。请注意,我只处理了 Call指令,我不确定如何在这里正确处理其他调用指令,甚至如果这是可能的。

警告:请注意,因为我只处理了那条指令,所以这将只适用于静态编译的调用。

虚拟调用,通过接口(interface)调用,恰好返回到同一个方法,不会被这个检测到,为此需要更高级的代码。

关于c# - 检测 C# 代码中的递归调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18076673/

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