c# - 任何方法到 "Safely"调用 assembly.GetTypes()?

标签 c# reflection

我到处搜索,但找不到解决方案。

我需要使用如下代码从程序集中获取所有接口(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/

相关文章:

c# - FROM 字符串的泛型类型转换

c# - 如何重新编号 WordProcessingDocument 中的页面?

c# - 是否可以在 C# 中为数组类型起别名?

c# - 在每个类中调用相同方法的最佳方法是什么?

c# - 在 C# 中解析用引号引起来的 CSV 文件

java - 使用反射访问java中子类和父类(super class)的属性

reflection - 为什么我不能使用反射来获取 slice 的地址?

reflection - 我可以替换Linqpad使用的反射工具吗?

java - 从java中的类对象运行任意函数

c# - 创建具有任意参数的委托(delegate)