从Mono.Cecil获取.NET类型

时间:2020-07-05 20:25:27

标签: c# mono.cecil

我正在开发.NET应用程序。在我的应用程序中,我必须检查程序集中的类型是否实现了特定的接口。我的程序集具有NuGet程序包(依赖项)中的程序包,因此我正在使用Mono.Cecil获取程序集中的所有类型。代码是:

ModuleDefinition module = ModuleDefinition.ReadModule(assemblyPath);
Collection<TypeDefinition> t1 = module.Types;

问题是Mono.Cecil返回 TypeDefinition ,而不是 Type 。因此,无论如何,我可以将集合中的每个 TypeDefinition 转换为 .NET Type ,以便我可以轻松地检查该类型是否实现了特定的接口?

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

如果可以使用接口的全名,则您不需要TypeTypeDefinition就足够了。示例(在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"|]
相关问题