猿问

调用Assembly.GetTypes()时如何防止ReflectionTypeLoad

我正在尝试使用类似于以下代码的程序集来扫描实现特定接口的类型的类型:


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;

}

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


就我而言,我对引起问题的类型不感兴趣。我要搜索的类型不需要不可用的程序集。


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


明月笑刀无情
浏览 747回答 3
3回答

潇潇雨雨

一种相当讨厌的方式是:Type[] types;try{&nbsp; &nbsp; types = asm.GetTypes();}catch (ReflectionTypeLoadException e){&nbsp; &nbsp; types = e.Types;}foreach (var t in types.Where(t => t != null)){&nbsp; &nbsp; ...}但是绝对必须这样做。您可以使用扩展方法在“客户端”代码中使其更美观:public static IEnumerable<Type> GetLoadableTypes(this Assembly assembly){&nbsp; &nbsp; // TODO: Argument validation&nbsp; &nbsp; try&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return assembly.GetTypes();&nbsp; &nbsp; }&nbsp; &nbsp; catch (ReflectionTypeLoadException e)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return e.Types.Where(t => t != null);&nbsp; &nbsp; }}您可能希望将return语句从catch块中移出-我不是很热衷于自己在其中,但是它可能是最短的代码...

长风秋雁

就我而言,相同的问题是由应用程序文件夹中存在不需要的程序集引起的。尝试清除Bin文件夹并重建应用程序。
随时随地看视频慕课网APP
我要回答