aj.*_*ler 5 c# clr cil mono.cecil
我试图找到给定类型所依赖的所有类型,包括接口,抽象类,枚举,结构等。我想加载程序集,并打印出其中定义的所有类型的列表,以及他们的依赖性。
到目前为止,我已经能够找到使用CLR程序集依赖于Mono.Cecil的所有外部类型,例如
using System;
using Mono.Cecil;
using System.IO;
FileInfo f = new FileInfo("SomeAssembly.dll");
AssemblyDefinition assemDef = AssemblyFactory.GetAssembly (f.FullName);
List<TypeReference> trList = new List<TypeReference>();
foreach(TypeReference tr in assemblyDef.MainModule.TypeReferences){
trList.Add(tr.FullName);
}
Run Code Online (Sandbox Code Playgroud)
也可以使用单声道反汇编程序获得此列表,例如“ monodis SomeAssembly.dll --typeref”,但此列表似乎不包括基本元素,例如System.Void,System.Int32等。
我需要分别对待每种类型,并获取给定类型所依赖的所有类型,即使这些类型在同一程序集中定义也是如此。有没有办法使用Mono.Cecil或任何其他项目来做到这一点?
我知道可以通过以下方法完成:加载程序集,然后遍历每个定义的类型,然后加载该类型的IL并对其进行扫描以查找引用,但是我相信有更好的方法。理想情况下,它还将与匿名内部类一起使用。
如果在同一程序集中定义了多个模块,它也应该起作用。
AJ,我遇到了同样的问题,我需要遍历程序集中的类型,然后我决定使用 Mono.Cecil。我能够遍历每个类以及类中的属性不是另一个类而不是 CLR 类型的方式是通过递归函数。
private void BuildTree(ModuleDefinition tempModuleDef , TypeDefinition tempTypeDef, TreeNode rootNode = null)
{
AssemblyTypeList.Add(tempTypeDef);
TreeNode tvTop = new TreeNode(tempTypeDef.Name);
// list all properties
foreach (PropertyDefinition tempPropertyDef in tempTypeDef.Properties)
{
//Check if the Property Type is actually a POCO in the same Assembly
if (tempModuleDef.Types.Any(q => q.FullName == tempPropertyDef.PropertyType.FullName))
{
TypeDefinition theType = tempModuleDef.Types.Where( q => q.FullName == tempPropertyDef.PropertyType.FullName)
.FirstOrDefault();
//Recursive Call
BuildTree(tempModuleDef, theType, tvTop);
}
TreeNode tvProperty = new TreeNode(tempPropertyDef.Name);
tvTop.Nodes.Add(tvProperty);
}
if (rootNode == null)
tvObjects.Nodes.Add(tvTop);
else
rootNode.Nodes.Add(tvTop);
}
Run Code Online (Sandbox Code Playgroud)
该函数由我的主函数调用,其要点是
public void Main()
{
AssemblyDefinition assemblyDef = AssemblyDefinition.ReadAssembly(dllname);
//Populate Tree
foreach (ModuleDefinition tempModuleDef in assemblyDef.Modules)
{
foreach (TypeDefinition tempTypeDef in tempModuleDef.Types)
{
BuildTree(tempModuleDef ,tempTypeDef, null);
}
}
}
Run Code Online (Sandbox Code Playgroud)