得到的组件定义的类型只 [英] Get Types defined in an assembly only

查看:106
本文介绍了得到的组件定义的类型只的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  

可能重复:
  <一href="http://stackoverflow.com/questions/7889228/how-to-$p$pvent-reflectiontypeloadexception-when-calling-assembly-gettypes">How以prevent ReflectionTypeLoadException调用Assembly.GetTypes时()

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

  

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

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

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

例如。替换

  .Assembly.GetTypes()式(T =&GT; t.Namespace.Equals(...
 

解决方案

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

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

    返回类型;
}
 

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;    
}

这篇关于得到的组件定义的类型只的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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