2016-11-04 21 views
0

我正在处理项目以清理遗留代码,并且需要以编程方式查找调用.NET 4.5服务引用(即Reference.cs文件)中的某些SOAP Web方法的所有引用我可以输出到文本文件或Excel(基本上,CodeLens功能列出的参考)。我想我会使用Mono.Cecil库来完成这项任务。列出使用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

我不喜欢这样写道:

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); 
       } 
      } 
     } 
    } 
相关问题