列出使用Mono.Cecil调用方法的所有引用

时间:2016-11-04 23:54:20

标签: c# .net reflection mono

我正在开发一个清理遗留代码的项目,需要以编程方式查找在.NET 4.5服务引用中调用某些SOAP Web方法的所有引用(即Reference.cs文件),这样我就可以输出到文本文件或Excel(基本上,与CodeLens功能一起列出的引用)。我想我会使用Mono.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
                        }
                    }
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我这样做:

 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);
                }
            }
        }
    }