如何使用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()
        {
        }
    }
}
复制代码

 

posted @   星辰与大海  阅读(788)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· Qt个人项目总结 —— MySQL数据库查询与断言
点击右上角即可分享
微信分享提示