问题
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