列出所有引用调用使用Mono.Cecil能的方法(List all references calli

2019-09-26 09:40发布

我工作的一个项目,清理遗留代码,并需要以编程方式找到的所有引用调用某些SOAP Web方法在.NET 4.5服务引用(即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
                        }
                    }
                }
            }
        }
    }
}

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


文章来源: List all references calling a method using Mono.Cecil