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");
}
}
}
}
當你s唉,「這一行不行」,你能夠確定它不起作用的任何特定方式嗎?它是不是編譯,它是否會拋出異常,返回null,還是隻是讓你在你的問題中提到的皺眉臉?你有沒有在MSDN中查看皺眉的臉,看看有沒有什麼有用的東西? –
這一行不完整(不編譯)我把它放在這裏只是爲了說明我嘗試過的東西。我GOOGLE了很多,我發現,這個問題可以通過Activator.CreateInstance解決,但我不能讓它工作。目前Iam正在尋找全新的idela如何解決我的問題。 – MrIncognito
在你的代碼中包含'namespace',因爲這就是你所缺少的。 – muratgu