通过字符串创建实例并添加到集合中

Creating instance by string and adding to collection

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

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 Parent {

}

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");
        }
    }
}

}

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;
}

您需要为您的 类:

提供命名空间
string[] types = { "MyApplication.Child1", "MyApplication.Child2" };

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

Parent parent = Activator.CreateInstance(Type.GetType(this.types[0]));