Create List<> from runtime type

后端 未结 3 1663
别跟我提以往
别跟我提以往 2020-12-31 06:10

I am looking to create a List, where the type of T is several unrelated classes (with the same constructor arguments) that I know through reflection.

    Dat         


        
相关标签:
3条回答
  • 2020-12-31 06:42

    You're confusing types and the System.Type class for Generic Type Parameters, here is the code to implement it the way you want:

    var lt = typeof(List<>);
    foreach (Type T in Types)
    {
        var l = Activator.CreateInstance(lt.MakeGenericType(T));
        DataBase.Add(l);
    }
    
    0 讨论(0)
  • 2020-12-31 06:47

    You could... use List<object> (if you know that your type is a reference type, or boxing is acceptable); or create a List via reflection.

    0 讨论(0)
  • 2020-12-31 06:52

    You can use reflection:

    List<object> database = new List<object>();
    foreach (Type t in Types)
    {
       var listType = typeof(List<>).MakeGenericType(t);
       database.Add(Activator.CreateInstance(listType));
    }
    
    0 讨论(0)
提交回复
热议问题