我到处搜索,但找不到解决方案。
我需要使用如下代码从程序集中获取所有接口(interface)类型:
IEnumerable<Type> interfaces = _assembly.GetTypes().Where(x => x.IsInterface);
问题是,对于某些程序集,我遇到了以下错误:
Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
我完全清楚为什么会发生这种情况(未加载依赖程序集),以及如果我想对特定程序集进行故障排除时如何解决。就我而言,我不知道前面的程序集(用户会选择它)。
我想知道的是,是否有任何方法可以让代码继续通过任何无法检索的类型,并仍然提取不会失败的类型。
最佳答案
看起来这是一个令人烦恼的 API,无法避免异常(据我所知)。
尝试这样的事情:
IEnumerable<Type> interfaces;
try
{
interfaces = _assembly.GetTypes().Where(x => x.IsInterface);
}
catch (ReflectionTypeLoadException ex)
{
interfaces = ex.Types.Where(x => x != null && x.IsInterface);
}
更新
实际上,这太丑陋了,我可能会把它藏在某个地方。这一定是 .NET Framework 中非常古老的部分,因为我敢肯定他们现在不会这样设计了。
private static IEnumerable<Type> GetTypesSafely(Assembly assembly)
{
try
{
return assembly.GetTypes();
}
catch(ReflectionTypeLoadException ex)
{
return ex.Types.Where(x => x != null);
}
}
...
IEnumberable<Type> interfaces = GetTypesSafely(_assembly).Where(x => x.IsInterface);
如果您认为自己会经常这样做,那么扩展方法可能更合适。
关于c# - 任何方法到 "Safely"调用 assembly.GetTypes()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5639380/