2016-06-28 4 views
1

文字列名でクラスのインスタンスを作成しようとしています。 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"); 
     } 
    } 
} 

}

+0

ay "この行は動作していません"、動作しない特定の方法を識別できるかどうかそれはコンパイルされないか、例外をスローするか、ヌルを返すか、それともあなたの質問にあなたが言及したような顔を作るだけですか?あなたはMSDNでおしゃれな顔を見て、それについて何か助けがあるかどうかを見ましたか? –

+0

この行は完全には機能していません(コンパイルされません)私は試したものだけをここに入れています。私はそれをたくさん見つけたと私は、この問題はActivator.CreateInstanceによって解決することができますが、私はそれを動作させることができないことがわかった。現在、私の問題を解決する方法を完全に新しいidelaを探しています。 – MrIncognito

+1

あなたのコードに 'namespace'が含まれています。なぜなら、あなたが欠けているものだからです。 – muratgu

答えて

2

それを使用する前に発見されたかどうかを確認します。次に

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

を、あなたはインスタンスを作成することができます実際のタイプを使用:

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

私はすでにそれを試しましたが、それは常に私にエラーを与えますArgumentNullException:引数はnullにすることはできません。 – MrIncognito

+0

@MrIncognitoは、あなたが使用した名前空間と試したものであなたの質問を更新します。 – muratgu

1

(問題は、名前空間が不足していた)コードを動作していますあなたはタイプを提供する必要があります。その後

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; 
} 
関連する問題