Get Types defined in an assembly only [duplicate]

喜欢而已 提交于 2019-12-10 20:49:49

问题


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(...

回答1:


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


来源:https://stackoverflow.com/questions/12885932/get-types-defined-in-an-assembly-only

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!