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

标签 c# visual-studio recursion resharper code-analysis

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

如果我在 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/

相关文章:

java - 将 for 循环重写为递归方法?

c# - 解决依赖构建的算法是什么?

vb.net - Visual Studio 2013 VB 智能感知

Php 按值传递对象

html - 在 MVC 中链接样式表的正确路径

c - _acrt_AppPolicyGetProcessTerminationMethodInternal 中的 popen 和 fgets 死锁

javascript - 如何在 while 循环内异步发出后续 http 请求而不使用 Promise 和 async/await?

c# - 测量在 Web 服务的每一层花费的时间

c# - 工具提示气球显示位置(用于错误通知)

c# - 如何使用透明度/alpha 在 Canvas 上绘制图像