从文本类名实例化List <class>

时间:2017-05-24 16:01:55

标签: c# class reflection types instance

我想知道是否有可能从文本类名实例化实例列表。 例如,我有以下代码:

List<Person> Persons;

我想对某些对象指定类名称进行这种控制:

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

如果有可能使用反射,请帮助我,谢谢。

1 个答案:

答案 0 :(得分: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;}
}