[英]Detect Recursive calls in C# code
我想在我的代碼中找到所有遞歸調用。
如果我在 Visual Studio 中打開文件,我會在編輯器的左側看到“遞歸調用”圖標。
我想檢查此類調用的整個解決方案。
我使用了 Resharper 命令行工具和 VS 的插件 Resharper - 代碼檢查,但運氣不佳,此規則未應用於他們的規則集中。
有什么方法可以檢查整個解決方案 - 我真的不想打開每個文件並檢查那個藍色的“遞歸調用”圖標:)
編輯:我對單級遞歸感興趣
你可以用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");
}
這將輸出直接調用自己的方法。 請注意,我只處理的呼叫指令,我不能確定如何處理其他調用指令正確位置,或者即使是甚至有可能。
警告:請注意,因為我只處理了那條指令,所以這將只適用於靜態編譯的調用。
虛擬調用,通過接口調用,恰好回到同一個方法,不會被檢測到,為此需要更多高級代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.