从程序集加载类型,遇到 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

作者:JasonGrass

出处:https://www.cnblogs.com/jasongrass/p/11990633.html

版权:本作品采用「署名 4.0 国际」许可协议进行许可。

posted @   J.晒太阳的猫  阅读(365)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
more_horiz
keyboard_arrow_up light_mode palette
选择主题
menu
点击右上角即可分享
微信分享提示