代码之家  ›  专栏  ›  技术社区  ›  Tim Cooper

从字符串创建类实例

  •  4
  • Tim Cooper  · 技术社区  · 15 年前

    我有一个C方法,它从一个字符串创建一个类的新实例,但是,当运行代码时,我会得到一个错误。

    obj = (ClassX)Activator.CreateInstance(Type.GetType("classPrefix_" + className));
    

    ArgumentNullException未处理

    值不能为空

    参数名称: 类型

    如有任何帮助,我们将不胜感激。

    7 回复  |  直到 13 年前
        1
  •  5
  •   Amal Sirisena    15 年前

    您可能需要使用程序集限定名作为type.gettype的参数。

    eg AssemblyName.Namespace.ClassName
    

    MSDN Doc on assembly qualified names

        2
  •  3
  •   zincorp    15 年前

    您可能只是缺少类名中的命名空间

        3
  •  1
  •   Mark Byers    15 年前

    为我工作:

    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
    

    不能定义要查找的类。您确定输入正确吗?

        4
  •  0
  •   Otávio Décio    15 年前

    你可能没有一个“classprefix”加上你在classname上拥有的任何东西。getType()调用返回空值,createInstance抛出argumentNullException。

        5
  •  0
  •   Nick Craver    15 年前

    这是因为 Type.GetType(classHere) 找不到任何东西,您确定您所用的类名存在吗?请记住,如果可能的话,它应该以名称空间为前缀,并且在外部程序集中找不到它,除非它已经加载到应用程序域中。

        6
  •  0
  •   aaronb    15 年前

    看起来像 Type.GetType("classPrefix_" + className) 正在返回空值。

    如果找不到类型,则返回空值。有两个可能的原因是缺少命名空间,或者类所在的程序集尚未加载。

    关于该方法的API文档可能会给出更多的信息。 http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx

        7
  •  0
  •   adrianbanks    15 年前

    看起来像你的 Type.GetType("classPrefix_" + className) 呼叫正在返回 null .这导致了 ArgumentNullException 当传递给 CreateInstance 方法。

    评价 "classPrefix_" + className 并检查是否有一个名为其计算结果的类型。

    您还应该指定 AssemblyQualifiedName 当使用 Type.GetType 方法(即完全限定的类型名,包括程序集名称和命名空间)。