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