Loading

从程序集加载类型,遇到 ReflectionTypeLoadException 的处理办法

处理办法

catch ReflectionTypeLoadException ,然后从里面读取 Types 数据(成功加载的类型)就可以了。

参考

ReflectionTypeLoadException Class (System.Reflection) | Microsoft Docs

.net - How to prevent ReflectionTypeLoadException when calling Assembly.GetTypes() - Stack Overflow

代码封装


    class AssemblyTypesDetector
    {
        public Assembly Assembly { get; }

        public Exception Exception { get; private set; }

        public AssemblyTypesDetector(Assembly assembly)
        {
            Assembly = assembly;
        }

        public AssemblyTypesDetector(string filePath)
        {
            Assembly = Assembly.LoadFile(filePath);
        }

        public AssemblyTypesDetector(AssemblyName assemblyName)
        {
            Assembly = Assembly.Load(assemblyName);
        }

        public IList<Type> DetectTypes()
        {
            Type[] types = null;
            try
            {
                types = Assembly.GetTypes().ToArray();
            }
            catch (ReflectionTypeLoadException reflectionTypeLoadException)
            {
                types = reflectionTypeLoadException.Types.Where(t => t != null).ToArray();
            }
            catch (Exception ex)
            {
                Exception = ex;
            }

            return types?.ToList() ?? new List<Type>();
        }

        public IList<Type> DetectTypes(Predicate<Type> predicate)
        {
            return DetectTypes().Where(predicate.Invoke).ToList();
        }

    }

原文链接:
https://www.cnblogs.com/jasongrass/p/11990633.html

posted @ 2019-12-05 17:28  J.晒太阳的猫  阅读(353)  评论(0编辑  收藏  举报