2016-06-28 37 views
1

Iam尝试按字符串名称创建类的实例。 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"); 
    } 
} 

我finnaly使它的工作。谢谢你们。这里是工作的代码(问题是缺少命名空间)

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

}

+0

当你s唉,“这一行不行”,你能够确定它不起作用的任何特定方式吗?它是不是编译,它是否会抛出异常,返回null,还是只是让你在你的问题中提到的皱眉脸?你有没有在MSDN中查看皱眉的脸,看看有没有什么有用的东西? –

+0

这一行不完整(不编译)我把它放在这里只是为了说明我尝试过的东西。我GOOGLE了很多,我发现,这个问题可以通过Activator.CreateInstance解决,但我不能让它工作。目前Iam正在寻找全新的idela如何解决我的问题。 – MrIncognito

+1

在你的代码中包含'namespace',因为这就是你所缺少的。 – muratgu

回答

2

你需要为你的类命名空间之前发现:

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

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

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

我已经尝试了它,但它总是给我错误ArgumentNullException:参数不能为空。 – MrIncognito

+0

@MIncognito用你使用的命名空间和你试过的任何东西来更新你的问题。 – muratgu

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; 
} 
相关问题