用C#代码检测递归调用 [英] Detect Recursive calls in C# code

查看:256
本文介绍了用C#代码检测递归调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to find all recursive calls in my code.

如果我在Visual Studio中打开文件,则会在编辑器左侧看到递归调用"图标.

If I open file in Visual Studio, I get "Recursive call" icon on left side of Editor.

我想检查这种呼叫的整个解决方案.

I want to inspect whole solution for such calls.

我使用了Resharper命令行工具和VS的加载项Resharper-代码检查,但是没有运气,该规则未应用在他们的规则集中.

I used Resharper Command Line tools and VS's add-in Resharper - Code Inspection with no luck, this rule is not applied in their ruleset.

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

Is there any way that i could inspect whole solution - i really don't want to open each file and check for that blue-ish "Recursive call" icon :)

我对单级递归感兴趣

推荐答案

可以使用 Mono做到这一点.Cecil .

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

Here is a simple LINQPad program that demonstrates:

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 指令,不确定如何正确处理其他呼叫指令,甚至不确定是否可能正确处理 .

This will output the methods that calls themselves directly. Note that I only processed the Call instruction, I'm not certain how to handle the other call instructions correctly here, or even if that is even possible.

注意事项:请注意,这是因为我只处理一条指令,因此只能用于静态编译的调用.

Caveat: Note that this will, because I only handled that single instruction, only work with statically compiled calls.

虚拟调用(通过接口进行的调用)恰好回到相同的方法,因此不会被检测到,为此需要更多高级代码.

Virtual calls, calls through interfaces, that just happen to go back to the same method, will not be detected by this, a lot more advanced code is necessary for that.

这篇关于用C#代码检测递归调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆