简体   繁体   中英

Finding type hierarchy assemblies using Mono.Cecil

I am trying to implement a method that receives a type and returns all the assemblies that contain its base types.

For example:
Class A is a base type (class A belongs to assembly c:\\A.dll )
Class B inherits from A (class B belongs to assembly c:\\B.dll )
Class C inherits from B (class C belongs to assembly 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" }
}

My main problem is that AssemblyDefinition from Mono.Cecil does not contain any property like Location .

How can an assembly location be found given an AssemblyDefinition ?

An assembly can be composed of multiple modules, so it doesn't really have a location per se. The assembly's main module does have a location though:

AssemblyDefinition assembly = ...;
ModuleDefinition module = assembly.MainModule;
string fileName = module.FullyQualifiedName;

So you could write something along the line of:

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

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

        type = type.BaseType.Resolve ();
    }
}

Or any other variant which pleases you more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM