调用 Assembly.GetTypes() 时如何防止 ReflectionTypeLoadException [英] How to prevent ReflectionTypeLoadException when calling Assembly.GetTypes()

查看:35
本文介绍了调用 Assembly.GetTypes() 时如何防止 ReflectionTypeLoadException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用与此类似的代码扫描程序集以查找实现特定接口的类型:

I'm trying to scan an assembly for types implementing a specific interface using code similar to this:

public List<Type> FindTypesImplementing<T>(string assemblyPath)
{
    var matchingTypes = new List<Type>();
    var asm = Assembly.LoadFrom(assemblyPath);
    foreach (var t in asm.GetTypes())
    {
        if (typeof(T).IsAssignableFrom(t))
            matchingTypes.Add(t);
    }
    return matchingTypes;
}

我的问题是,在某些情况下,例如调用 asm.GetTypes() 时,我会收到 ReflectionTypeLoadException如果程序集包含引用当前不可用的程序集的类型.

My problem is, that I get a ReflectionTypeLoadException when calling asm.GetTypes() in some cases, e.g. if the assembly contains types referencing an assembly which is currently not available.

就我而言,我对导致问题的类型不感兴趣.我正在搜索的类型不需要不可用的程序集.

In my case, I'm not interested in the types which cause the problem. The types I'm searching for do not need the non-available assemblies.

问题是:是否有可能以某种方式跳过/忽略导致异常的类型,但仍处理程序集中包含的其他类型?

The question is: is it possible to somehow skip/ignore the types which cause the exception but still process the other types contained in the assembly?

推荐答案

一种相当讨厌的方法是:

One fairly nasty way would be:

Type[] types;
try
{
    types = asm.GetTypes();
}
catch (ReflectionTypeLoadException e)
{
    types = e.Types;
}
foreach (var t in types.Where(t => t != null))
{
    ...
}

虽然这样做确实很烦人.您可以在客户端"代码中使用扩展方法使其更好:

It's definitely annoying to have to do this though. You could use an extension method to make it nicer in the "client" code:

public static IEnumerable<Type> GetLoadableTypes(this Assembly assembly)
{
    // TODO: Argument validation
    try
    {
        return assembly.GetTypes();
    }
    catch (ReflectionTypeLoadException e)
    {
        return e.Types.Where(t => t != null);
    }
}

您可能希望将 return 语句移出 catch 块 - 我本人并不是非常希望它在那里,但它可能是最短的代码...

You may well wish to move the return statement out of the catch block - I'm not terribly keen on it being there myself, but it probably is the shortest code...

这篇关于调用 Assembly.GetTypes() 时如何防止 ReflectionTypeLoadException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆