按字符串创建实例并添加到集合

时间:2016-06-28 17:16:05

标签: c# system.reflection

我试图通过字符串名称创建类的实例。 Iam创建实用程序,用户从字符串的弹出框中选择类型(该字段的内容是字段的内容"类型")我需要根据他的选择创建类的实例。不幸的是,我完全不知道该怎么做

class Parent
{

}

class Child1 : Parent
{

}

class Child2 : Parent
{

}

string[] types = { "Child1", "Child2" };
List<Parent> collection = new List<Parent>(); 

void Main()
{
    Parent newElement = Activator.CreateInstance(this.types[0]) as Parent;  // this row is not working :( and I dont know how to make it work

    this.collection.Add(newElement);
    if (this.collection[0] is Child1)
    {
        Debug.Log("I want this to be true");
    }
    else
    {
        Debug.Log("Error");
    }
}

我最终使它成功。谢谢你们。这是工作代码(问题在于缺少命名空间)

namespace MyNamespace

{     班级家长     {

}

class Child1 : Parent
{

}

class Child2 : Parent
{

}

class Main
{
    string[] types = { typeof(Child1).ToString(), typeof(Child2).ToString() };
    List<Parent> collection = new List<Parent>(); 

    public void Init()
    {
        Parent newElement = Activator.CreateInstance(Type.GetType(this.types[0])) as Parent;

        this.collection.Add(newElement);
        if (this.collection[0] is Child1)
        {
            Debug.Log("I want this to be true");
        }
        else
        {
            Debug.Log("Error");
        }
    }
}

}

2 个答案:

答案 0 :(得分:2)

您需要为您的类提供命名空间:

NET USE M: /delete /yes 2>nul

然后,您可以使用实际类型创建实例:

string[] types = { "MyApplication.Child1", "MyApplication.Child2" };

答案 1 :(得分:1)

Activator.CreateInstance方法不将字符串作为参数。您需要提供类型。

Type parentType = Type.GetType(types[0],false); //param 1 is the type name.  param 2 means it wont throw an error if the type doesn't exist

然后在使用之前检查是否找到了类型

if (parentType != null)
{
    Parent newElement = Activator.CreateInstance(parentType) as Parent;
}