2016-06-28 40 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; 
} 
相關問題