C#通过类全名字符串创建实例时GetInstance始终返回null
反射根据完全限定名创建实例始终返回null的问题排查
错误原因
核心问题是传入的类型完全限定名不符合反射API的解析规则:
- 命名空间和类型之间用
.分隔是正确的,但嵌套在其他类/静态类内部的类型,和外层类型之间必须用+分隔,反射接口才能正确识别。
你的CarPainted是定义在静态类Features内部的嵌套类,传入的字符串MyApp.Domain.Cars.Features.CarPainted用.连接外层类Features和内部类CarPainted,反射逻辑会把Features.CarPainted当成命名空间下的平级类型,自然找不到匹配结果,最终返回null。
除此之外你贴的GetInstance方法还存在返回路径缺失的问题:如果遍历完所有已加载程序集都没找到对应类型,方法没有显式返回值,会触发编译错误。
修正代码
首先修正完全限定名的格式,再补全方法的兜底返回:
namespace MyApp.Domain.Cars; public static class Features { public class CarPainted { public Guid CarId { get; set; } // 其余属性定义 } } // 修正嵌套类型的完全限定名格式,外层类和嵌套类用+连接 string fqn = "MyApp.Domain.Cars.Features+CarPainted"; var carPaintedObject = GetInstance(fqn); private static object GetInstance(string strFullyQualifiedName) { Type type = Type.GetType(strFullyQualifiedName); if (type != null) return Activator.CreateInstance(type); foreach (var asm in AppDomain.CurrentDomain.GetAssemblies()) { type = asm.GetType(strFullyQualifiedName); if (type != null) return Activator.CreateInstance(type); } // 补全未找到类型时的返回逻辑 return null; }
补充注意点
- 你可以通过
typeof(Features.CarPainted).FullName直接输出对应类型的正确完全限定名,避免手写格式出错。 - 如果目标类型定义在尚未加载到当前应用域的程序集中,遍历
AppDomain.CurrentDomain.GetAssemblies()也无法找到类型,需要先手动加载对应程序集再执行查找。 - 如果目标类型没有无参构造函数,直接调用
Activator.CreateInstance(type)会抛出异常,需要传入构造函数参数匹配对应重载。
内容的提问来源于stack exchange,提问作者user1765862
相关产品推荐
相关产品推荐

