从 Mono.Cecil 获取 .NET 类型



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

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

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

任何帮助将不胜感激。

如果您可以使用接口的全名,那么您不需要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"|]

最新更新