2017-05-24 2 views
1

テキストクラス名からインスタンスのインスタンスをインスタンス化する可能性があるかどうかを知りたいと思います。 例えば、私は以下のコードがあります。リストのインスタンス化<class>テキストクラス名から

List<Person> Persons; 

を私はいくつかのオブジェクトのクラス名をspecifiyingにこのような制御を持っているしたいと思います:

string ClassName = "Person"; 
List<ClassName> Persons; 

リフレクションを使用して、いくつかの可能性がある場合は、してください助けてください、ありがとう。

+8

あなたは最終的に何をしようとしていますか? – Sweeper

答えて

0

次のコードは、Linqpadで出力を確認するために実行します。重要な方法はType.MakeGenericTypeです。

実際の使用例や要件を示していれば、コードを微調整してもう少し役に立ちます。

void Main() 
{ 
    string className = "UserQuery+Person"; 
    Type personType = Type.GetType(className); 
    Type genericListType = typeof(List<>); 

    Type personListType = genericListType.MakeGenericType(personType); 

    IList personList = Activator.CreateInstance(personListType) as IList; 

    // The following code is intended to demonstrate that this is a real 
    // list you can add items to. 
    // In practice you will typically be using reflection from this point 
    // forwards, as you won't know at compile time what the types in 
    // the list actually are... 
    personList.Add(new Person { Name = "Alice" }); 
    personList.Add(new Person { Name = "Bob" }); 

    foreach (var person in personList.Cast<Person>()) 
    { 
     Console.WriteLine(person.Name); 
    } 
} 

class Person 
{ 
    public string Name { get; set;} 
} 
+0

'className ==" SomeClassNameOtherThanPerson "'の場合はどうなりますか?あなたのコードは 'Person'クラスでのみ動作し、他のクラスでは動作しません。 –

+0

'Activator.CreateInstance'の後のすべては、これが本当のリストであることを証明しようとしています。リストの使い方を説明していないので、純粋にその使い方のデモンストレーションを意図しています。これを明確にするためにコードを編集しました。 –

+0

ありがとうございます、それは私を助けてくれますが、はい、それは "Person Class"でしか動作しません。ここでの問題は、 "personList.Cast "と書かれているようにpersonListに "cast"ハードコードなしで?もう一度ありがとう! –

関連する問題