在我的项目中,我有以下辅助方法,它遍历所有程序集并获取属于 BaseCamaFrom 类型子类的所有类型。
public static List<Type> GetAllTestActionFormTypes()
{
List<Type> types = new List<Type>();
// add all the types that are subclasses of BaseCamaForm to the _camaFormType list
foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
foreach (Type t in asm.GetTypes())
if (t.IsSubclassOf(typeof(BaseCamaForm)))
types.Add(t);
return types;
}
此方法在第一次调用时工作正常。但是,第二次调用此方法时,调用 asm.GetTypes()
时会发生以下异常:
ReflectionTypeLoadException was unhandled by user code: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
在查看 LoaderException 属性时,我发现了一个带有以下消息的 System.IO.FileLoadException
:
Mixed mode assembly is built against version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.
为什么这段代码在第一次调用时有效,但第二次总是异常?
编辑:经过更多调查,我引用的唯一运行时版本为 2.0.50727 的程序集是 Microsoft.TeamFoundation.Client 和 Microsoft.TeamFoundation.VersionControl.Client。我不明白为什么这些引用会导致反射问题,也不知道为什么它似乎只在第二次尝试时发生。当尝试对某些类使用
Activator.CreateInstance(types[x])
调用时,这似乎偶尔也会发生。
最佳答案
显然我必须添加 <startup useLegacyV2RuntimeActivationPolicy="true" />
进入我的 app.config 文件。一旦我这样做了,我就不再发生反射异常。我仍然不知道它为什么这样做,但至少它是固定的。
关于c# - 在 .net 4 中第二次尝试反射时获取 ReflectionTypeLoadException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3567559/