列出使用mono_cecil调用方法的所有引用



我正在做一个清理遗留代码的项目,需要以编程方式找到。net 4.5服务引用(即Reference.cs文件)中调用某些SOAP web方法的所有引用,以便我可以输出到文本文件或Excel(基本上,CodeLens功能列出的引用)。我想我应该用单声道。Cecil库。

我有指定程序集和类的方法工作得很好,因为我可以打印所有要检查的方法的列表。但是关于如何获得特定方法的参考列表,有什么想法吗?

// assemblyName is the file path for the specific dll   
public static void GetReferencesList(string assemblyName)
    {
        AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly(assemblyName);
        foreach (ModuleDefinition module in assembly.Modules)
        {
            foreach (TypeDefinition type in module.Types)
            {
                if (type.Name.ToLowerInvariant() == "classname")
                {
                    foreach (MethodDefinition method in type.Methods)
                    {
                        if (method.Name.Substring(0, 4) != "get_" &&
                            method.Name.Substring(0, 4) != "set_" &&
                            method.Name != ".ctor" &&
                            method.Name != ".cctor" &&
                            !method.Name.Contains("Async"))
                        {
                            //Method name prints great here
                            Console.WriteLine(method.Name);
                            // Would like to collect the list of referencing calls here
                            // for later output to text files or Excel
                        }
                    }
                }
            }
        }
    }
}

我是这样做的:

 static HashSet<string> BuildDependency(AssemblyDefinition ass, MethodReference method)
        {
            var types = ass.Modules.SelectMany(m => m.GetTypes()).ToArray();
            var r = new HashSet<string>();
            DrillDownDependency(types, method,0,r);
            return r;
        }
    static void DrillDownDependency(TypeDefinition[] allTypes, MethodReference method, int depth, HashSet<string> result)
    {
        foreach (var type in allTypes)
        {
            foreach (var m in type.Methods)
            {
                if (m.HasBody &&
                    m.Body.Instructions.Any(il =>
                    {
                        if (il.OpCode == Mono.Cecil.Cil.OpCodes.Call)
                        {
                            var mRef = il.Operand as MethodReference;
                            if (mRef != null && string.Equals(mRef.FullName,method.FullName,StringComparison.InvariantCultureIgnoreCase))
                            {
                                return true;
                            }
                        }
                        return false;
                    }))
                {
                    result.Add(new string('t', depth) + m.FullName);
                    DrillDownDependency(allTypes,m,++depth, result);
                }
            }
        }
    }

相关内容

  • 没有找到相关文章

最新更新