【发布时间】:2017-02-22 11:01:02
【问题描述】:
我有一个类型 Type,我希望在程序集中搜索派生类型。
出于性能原因,我正在尝试使用 Mono.Cecil 预扫描程序集。扫描和加载所有程序集花费的时间太长,并且建议 cecil 进行预扫描要快得多,因为只有一小部分可用的程序集具有匹配的类型。
到目前为止,我有以下仅适用于接口的内容。
private static IEnumerable<Type> MatchingTypesFromDll<TParent>(string dllPath)
{
var type = typeof(TParent);
if (!type.IsInterface)
throw new Exception("Only interfaces supported");
try
{
var assDef = Mono.Cecil.AssemblyDefinition.ReadAssembly(dllPath);
var types = assDef.Modules.SelectMany(m => m.GetTypes());
if (types.Any(t => t.Interfaces.Any(i=>i.FullName == type.FullName)))
{
var assembly = Assembly.LoadFrom(dllPath);
return assembly
.GetExportedTypes()
.Where(TypeSatisfies<TParent>);
}
else
{
return new Type[] {};
}
}
catch (Exception e)
{
return new Type[] { };
}
}
private static bool TypeSatisfies<TParent>(Type type)
{
return typeof (TParent).IsAssignableFrom(type)
&& !type.IsAbstract
&& !type.IsInterface;
}
我怎样才能将其扩展为也适用于基类?
【问题讨论】:
-
当你提到一个类时,
normal是什么意思? -
我的意思不是接口。
-
将“普通类”改为“基类”
标签: c# mono.cecil