I am working on a .NET application. In my application i have to check if the types in the assembly implement a particular interface. My assembly has a package from NuGet package (dependency) so i am using Mono.Cecil for getting all the types in the assembly. Code is:
ModuleDefinition module = ModuleDefinition.ReadModule(assemblyPath);
Collection<TypeDefinition> t1 = module.Types;
Issue is that Mono.Cecil return TypeDefinition and not Type . So is there anyway that i can convert each TypeDefinition in the collection to .NET Type so that i can easily check if that type implements a particular interface or not?
Any help would be much appreciated.
If it's OK for you to use the full name of the interface, then you don't need Type
, TypeDefinition
is enough. Example (in F#):
let myInterface = "Elastic.Apm.Api.ITracer"
let implementsInterface (t : Mono.Cecil.TypeDefinition) =
t.HasInterfaces
&& t.Interfaces |> Seq.exists (fun i -> i.InterfaceType.FullName = myInterface)
let getTypes assemblyFileName =
Mono.Cecil.AssemblyDefinition
.ReadAssembly(fileName = assemblyFileName).MainModule.Types
|> Seq.filter implementsInterface
|> Seq.map (fun t -> t.FullName)
|> Seq.toArray
let ts = getTypes assemblyFile
printfn "Types implementing %s: %A" myInterface ts
// Output:
// Types implementing Elastic.Apm.Api.ITracer: [|"Elastic.Apm.Api.Tracer"|]
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.