ReflectionTypeLoadException 无法加载一个或多个请求的类型

ReflectionTypeLoadException Unable to load one or > more of the requested types

我有以下代码,它加载了我的项目引用的所有组件以及它们使用的所有组件

var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(t => t.GetTypes())
                        .Where(t => t.IsClass && !t.IsAbstract && (typeof (MyType).IsAssignableFrom(t)));


foreach (var type in types.Where(type => typeof (MyType).IsAssignableFrom(type)))
                {... do something ...}

在我的开发箱上这按预期工作,在其他环境中这会导致异常

System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.

为什么抛出异常? 是否可以重构我的代码以忽略异常?

我遇到了完全相同的问题,但它遇到的问题我并不关心。

我从这里开始(在本地工作):

Type t = AppDomain.CurrentDomain.GetAssemblies()
              .SelectMany(a => a.GetTypes())
              .Where(a => a.FullName == clientEx.ExceptionType)
              .FirstOrDefault();

为此:

Type t = null;

foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
{
    try
    {
        foreach (Type type in a.GetTypes())
        {
            if (type.FullName == clientEx.ExceptionType)
            {
                t = type;
                break;
            }                                            
        }

        if (t != null)
            break;
    }
    catch (Exception) { }
}

在我的例子中,我需要从当前程序集中加载实现类型,所以这对我有用。

var types = (typeof(ClassinAssembly).Assembly)
                                            .GetTypes()
                                            .Where(x => typeof(IMyInterface).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract)
                                            .ToList();

foreach (var t in types)
{
  .....
}