从string创建类实例
我有一个C#方法,它从字符串创建一个类的新实例,但是,在运行代码时出现错误。
obj = (ClassX)Activator.CreateInstance(Type.GetType("classPrefix_" + className));
ArgumentNullException未处理
值不能为空
参数名称: 类型
任何有关此错误的帮助将不胜感激。
您可能需要使用程序集限定名作为Type.GetType的参数
eg AssemblyName.Namespace.ClassName
关于程序集限定名称的MSDN Doc
您可能只是从类名中缺少命名空间
适合我:
class ClassX {} class classPrefix_x : ClassX {} public class Program { public static void Main() { string className = "x"; ClassX obj = (ClassX)Activator.CreateInstance(Type.GetType("classPrefix_" + className)); Console.WriteLine(obj); } }
结果:
classPrefix_x
您要查找的课程不得定义。 你确定你输入正确吗?
您可能没有“classPrefix_”类型以及className上的任何内容。 Type.GetType()调用返回null,CreateInstance抛出ArgumentNullException。
这是因为Type.GetType(classHere)
没有找到任何内容,您确定您所在的类名是否存在? 请记住,如果可能,它应该以命名空间为前缀,并且除非已经在App域中加载,否则将无法在外部程序集中找到它。
看起来Type.GetType("classPrefix_" + className)
返回null。
当它找不到类型时返回null。 一些可能的原因是缺少命名空间,或者尚未加载该类所在的程序集。
关于该方法的Api文档可能会提供更多内容。 https://msdn.microsoft.com/en-us/library/w3f99sx1.aspx
看起来你的Type.GetType("classPrefix_" + className)
调用返回null
。 这会在传递给CreateInstance
方法时导致ArgumentNullException
。
评估"classPrefix_" + className
并检查您确实有一个名为它所评估的类型。
您还应该在使用Type.GetType方法时指定AssemblyQualifiedName (即包含程序集名称和命名空间的完全限定类型名称)。
上述就是C#学习教程:从string创建类实例分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/989140.html