zoukankan      html  css  js  c++  java
  • 如何使用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()
            {
            }
        }
    }
  • 相关阅读:
    【BZOJ2806】【CTSC2012】—熟悉的文章(二分答案+广义后缀自动机+单调队列优化dp)
    2017-2-15
    2017-2-14
    2017-2-13
    CSS居中
    2017-2-10
    微信小程序
    2017-2-9
    2017-2-8
    基础知识再整理: 01
  • 原文地址:https://www.cnblogs.com/davies/p/12012956.html
Copyright © 2011-2022 走看看