Create List<> from runtime type

后端 未结 3 1695
别跟我提以往
别跟我提以往 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);
    }
    

提交回复
热议问题