首页 > 其他 > 详细

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

时间:2019-12-09 19:51:40      阅读:169      评论:0      收藏:0      [点我收藏+]

 

参考网址: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()
        {
        }
    }
}

 

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

原文:https://www.cnblogs.com/davies/p/12012956.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!