如何使用Activator.CreateInstance创建一个列表<T>,其中T在运行时是未知的?

参考网址:https://cloud.tencent.com/developer/ask/185965

using System;
using System.Collections.Generic;
namespace ConsActivator
{
    class ActivatorHelper
    {
        public static void TestMain(string[] args)
        {
            var s1 = CreateListFromType(typeof(Foo));
            var s2 = CreateListFromType(typeof(int));
            var fo = new Foo();
            var s3 = CreateListFromType(fo.GetType());

            Console.WriteLine(s1.ToString());
            Console.WriteLine(s2.ToString());
            Console.WriteLine(s3.ToString());
            Console.WriteLine(fo.GetType().Name);
        }

        static object CreateListFromType(Type t)
        {
            // Create an array of the required type
            Array values = Array.CreateInstance(t, 50);

            // and fill it with values of the required type
            for (int i = 0; i < 50; i++)
            {
                values.SetValue(CreateFooFromType(t), i);
            }

            // Create a list of the required type, passing the values to the constructor
            Type genericListType = typeof(List<>);
            Type concreteListType = genericListType.MakeGenericType(t);

            object list = Activator.CreateInstance(concreteListType, new object[] { values });

            // DO something with list which is now an List<t> filled with 50 ts
            return list;
        }


        // Create a value of the required type
        static object CreateFooFromType(Type t)
        {
            return Activator.CreateInstance(t);
        }
    }
    class Foo
    {
        public Foo()
        {
        }
    }
}
原文地址:https://www.cnblogs.com/davies/p/12012956.html