从程序集加载类型,遇到 ReflectionTypeLoadException 的处理办法
处理办法
catch ReflectionTypeLoadException ,然后从里面读取 Types 数据(成功加载的类型)就可以了。
参考
ReflectionTypeLoadException Class (System.Reflection) | Microsoft Docs
.net - How to prevent ReflectionTypeLoadException when calling Assembly.GetTypes() - Stack Overflow
代码封装
class AssemblyTypesDetector
{
public Assembly Assembly { get; }
public Exception Exception { get; private set; }
public AssemblyTypesDetector(Assembly assembly)
{
Assembly = assembly;
}
public AssemblyTypesDetector(string filePath)
{
Assembly = Assembly.LoadFile(filePath);
}
public AssemblyTypesDetector(AssemblyName assemblyName)
{
Assembly = Assembly.Load(assemblyName);
}
public IList<Type> DetectTypes()
{
Type[] types = null;
try
{
types = Assembly.GetTypes().ToArray();
}
catch (ReflectionTypeLoadException reflectionTypeLoadException)
{
types = reflectionTypeLoadException.Types.Where(t => t != null).ToArray();
}
catch (Exception ex)
{
Exception = ex;
}
return types?.ToList() ?? new List<Type>();
}
public IList<Type> DetectTypes(Predicate<Type> predicate)
{
return DetectTypes().Where(predicate.Invoke).ToList();
}
}
作者:
J.晒太阳的猫
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。