我有一个 C# 方法,它从字符串创建类的新实例,但是,在运行代码时出现错误。
obj = (ClassX)Activator.CreateInstance(Type.GetType("classPrefix_" + className));
ArgumentNullException 未处理
值不能为空
参数名称:类型
对此错误的任何帮助将不胜感激。
我有一个 C# 方法,它从字符串创建类的新实例,但是,在运行代码时出现错误。
obj = (ClassX)Activator.CreateInstance(Type.GetType("classPrefix_" + className));
ArgumentNullException 未处理
值不能为空
参数名称:类型
对此错误的任何帮助将不胜感激。
您可能只是缺少类名中的命名空间
为我工作:
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
不得定义您要查找的类。你确定你输入正确吗?
看起来您的Type.GetType("classPrefix_" + className)
电话正在返回一个null
. 这导致ArgumentNullException
传递给CreateInstance
方法的时间。
评估"classPrefix_" + className
并检查您是否有一个类型,称为它评估的对象。
您还应该在使用Type.GetType方法时指定AssemblyQualifiedName(即,完全限定的类型名称,包括程序集名称和命名空间)。
您可能没有“classPrefix_”类型以及您在 className 上的任何内容。Type.GetType() 调用返回 null 并且 CreateInstance 引发 ArgumentNullException。
这是因为Type.GetType(classHere)
没有找到任何东西,你确定你所追求的类名存在吗?请记住,如果可能,它应该以命名空间为前缀,并且除非它已经加载到 App 域中,否则它不会在外部程序集中找到。
它看起来像Type.GetType("classPrefix_" + className)
返回null。
当找不到类型时,这将返回 null。几个可能的原因是缺少命名空间,或者该类所在的程序集尚未加载。
有关该方法的 Api 文档可能会提供更多内容。 http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx