我试图找到给定类型所依赖的所有类型,包括接口,抽象类,枚举,结构等。我想加载一个程序集,并打印出一个列表中列出的所有类型它和它们的依赖关系。
到目前为止,我已经能够找到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);
}
此列表也可以使用mono disasembler获得,例如“monodis SomeAssembly.dll --typeref”,但此列表似乎不包括原语,例如System.Void,System.Int32等
我需要单独处理每个类型,并获取给定类型所依赖的所有类型,即使类型是在同一个程序集中定义的。 有没有办法使用Mono.Cecil或任何其他项目?
我知道可以通过加载程序集,然后遍历每个定义的类型,然后加载类型的IL并扫描它以获取引用来完成,但我确信有更好的方法。理想情况下,它也适用于匿名内部类。
如果在同一个程序集中定义了多个模块,它也应该有效。
答案 0 :(得分:1)
看看NDepend - 它可以做到这一点,还有更多。
-Oisin
答案 1 :(得分:1)
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);
}
此函数由我的主要函数调用,其主要部分是
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);
}
}
}