文字列名でクラスのインスタンスを作成しようとしています。 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。皆さん、ありがとうございました。ここでActivator.CreateInstanceメソッドは、パラメータとしての文字列をとらない。
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");
}
}
}
}
ay "この行は動作していません"、動作しない特定の方法を識別できるかどうかそれはコンパイルされないか、例外をスローするか、ヌルを返すか、それともあなたの質問にあなたが言及したような顔を作るだけですか?あなたはMSDNでおしゃれな顔を見て、それについて何か助けがあるかどうかを見ましたか? –
この行は完全には機能していません(コンパイルされません)私は試したものだけをここに入れています。私はそれをたくさん見つけたと私は、この問題はActivator.CreateInstanceによって解決することができますが、私はそれを動作させることができないことがわかった。現在、私の問題を解決する方法を完全に新しいidelaを探しています。 – MrIncognito
あなたのコードに 'namespace'が含まれています。なぜなら、あなたが欠けているものだからです。 – muratgu