使用Mono.Cecil查找类型层次结构程序集

Eli*_*sha 5 c# reflection assemblies mono.cecil

我试图实现一个接收类型的方法,并返回包含其基类型的所有程序集.

例如:
Class A是基类型(类A属于程序集c:\ A.dll)
B继承自A(类B属于程序集c:\ B.dll)
C继承自B(类C属于程序集c:\ c.dll)

public IEnumerable<string> GetAssembliesFromInheritance(string assembly, 
                                                        string type)
{
    // If the method recieves type C from assembly c:\C.dll
    // it should return { "c:\A.dll", "c:\B.dll", "c:\C.dll" }
}
Run Code Online (Sandbox Code Playgroud)

我的主要问题是AssemblyDefinition来自Mono.Cecil不包含任何属性,如Location.

如何给出装配位置AssemblyDefinition

Jb *_*ain 5

一个程序集可以由多个模块组成,因此它本身并没有真正的位置。程序集的主模块确实有一个位置:

AssemblyDefinition assembly = ...;
ModuleDefinition module = assembly.MainModule;
string fileName = module.FullyQualifiedName;
Run Code Online (Sandbox Code Playgroud)

所以你可以写一些类似的东西:

public IEnumerable<string> GetAssembliesFromInheritance (TypeDefinition type)
{
    while (type != null) {
        yield return type.Module.FullyQualifiedName;

        if (type.BaseType == null)
            yield break;

        type = type.BaseType.Resolve ();
    }
}
Run Code Online (Sandbox Code Playgroud)

或任何其他更让您满意的变体。