标签: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);
}
此列表也可以使用mono disasembler获得,例如“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);
}
这个函数由我的主要函数调用,其主旨是
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);
}
}
}
标签:c,clr,cil,mono-cecil 来源: https://codeday.me/bug/20190705/1385561.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。