得到的组件定义的类型只组件、定义、类型

由网友(本是凉薄之人何必用情太深)分享简介:可能重复: How以prevent ReflectionTypeLoadException调用Assembly.GetTypes时() 我想获得的所有类型的组件。不过,我得到了以下错误:System.Reflection.ReflectionTypeLoadException:无法加载一个或更请求的类型。现在的问题是...

可能重复:   How以prevent ReflectionTypeLoadException调用Assembly.GetTypes时()

我想获得的所有类型的组件。不过,我得到了以下错误:

  

System.Reflection.ReflectionTypeLoadException:无法加载一个或   更请求的类型。

现在的问题是我收到的类型从被引用另一个组件,它只是在生产环境中可用的组件,而不是单元测试环境中。

那么,有没有什么办法,我可以过滤GetTypes或类似的东西只返回在装配实际定义的类型,而不是让负载类型的异常?

例如。替换

  .Assembly.GetTypes()式(T => t.Namespace.Equals(...
 

解决方案

GetTypes 只得到了在汇编中定义的类型,但是,您可能无法加载它们因为它们在引用是在没有装入或无法找到的组件的类型。例如,如果你尝试加载源自一类在这个其他组件的类型,那么你会得到一个 ReflectionTypeLoadException 。你可以得到你的异常对象的类型属性没有负载的类型。请注意,会有一个为每种类型的,你无法加载和 LoaderExceptions 酒店有例外的每它们。

 公共静态类型[] GetTypesLoaded(装配组装)
{
    键入[]类型;
    尝试
    {
      类型= assembly.GetTypes();
    }
    赶上(ReflectionTypeLoadException E)
    {
      类型= e.Types.Where(T =>吨!= NULL).ToArray();
    }

    返回类型;
}
 

Spark学习之路 2.核心组件 概念

Possible Duplicate: How to prevent ReflectionTypeLoadException when calling Assembly.GetTypes()

I would like to get all the types in an assembly. However, I get the following error:

System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types.

The problem is the assembly I am getting the types from is referencing another assembly that is only available in the production environment, and not within the unit test environment.

So, is there any way that I can filter GetTypes or something similar to only return the types actually defined in the assembly and not get the type load exception?

e.g. replacement for

.Assembly.GetTypes().Where(t => t.Namespace.Equals(...

解决方案

GetTypes only gets the types that are defined in the assembly, however, you may not be able to load them because they are referencing types that are in an assembly you have not loaded or cannot be found. For example, if you try to load a type that derives from a class in this other assembly then you get a ReflectionTypeLoadException. You can get the types that you did load from the exception object's Types property. Note that there will be a null for each type you could not load and the LoaderExceptions property has an exception for each of them.

public static Type[] GetTypesLoaded(Assembly assembly)
{
    Type[] types;
    try
    {
      types = assembly.GetTypes();
    }
    catch (ReflectionTypeLoadException e)
    {
      types = e.Types.Where(t => t != null).ToArray();
    }

    return types;    
}

阅读全文

相关推荐

最新文章