我正在开发一个.NET应用程序。在我的应用程序中,我必须检查程序集中的类型是否实现了特定的接口。我的程序集有一个来自NuGet包(依赖项)的包,所以我使用Mono.Cecil获取程序集中的所有类型。守则是:
ModuleDefinition module = ModuleDefinition.ReadModule(assemblyPath);
Collection<TypeDefinition> t1 = module.Types;问题是Mono.Cecil返回的是Mono.Cecil而不是类型。那么,我是否可以将集合中的每个TypeDefinition转换为.NET Type,以便轻松地检查该类型是否实现了特定的接口?
任何帮助都将不胜感激。
发布于 2020-07-05 21:10:09
如果您可以使用接口的全名,那么您不需要Type,TypeDefinition就足够了。示例(在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"|]https://stackoverflow.com/questions/62745949
复制相似问题