gpt4 book ai didi

c# - 如何在任何基于 COLOR 的语言汇编中找到给定类型的所有类型依赖项?

转载 作者:太空狗 更新时间:2023-10-29 23:42:34 25 4
gpt4 key购买 nike

我试图找到给定类型所依赖的所有类型,包括接口(interface)、抽象类、枚举、结构等。我想加载一个程序集,并打印出其中定义的所有类型的列表它,以及它们的依赖项。

到目前为止,我已经能够找到 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 反汇编器获得,例如“monodis SomeAssembly.dll --typeref”,但是这个列表似乎不包括原语,例如 System.Void、System.Int32 等

我需要单独处理每个类型,并获取给定类型所依赖的所有类型,即使这些类型是在同一个程序集中定义的。有没有办法使用 Mono.Cecil 或任何其他项目来做到这一点?

我知道这可以通过加载程序集来完成,然后遍历每个定义的类型,然后加载该类型的 IL 并扫描它以查找引用,但我确信有更好的方法。理想情况下,它也适用于匿名内部类。

如果在同一个程序集中定义了多个模块,它也应该可以工作。

最佳答案

阿杰, 我遇到了同样的问题,我需要遍历程序集中的类型,我决定使用 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# - 如何在任何基于 COLOR 的语言汇编中找到给定类型的所有类型依赖项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2061992/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com