首页 > 其他 > 详细

泛型,动态创建List<T> (转摘)

时间:2014-06-08 18:39:03      阅读:579      评论:0      收藏:0      [点我收藏+]

第一种:

 

       static void Main()
        {
            object intList = MakeList(typeof(int), 1, 2, 3);
            object strList = MakeList(typeof(string), "sdfd", "fet");

            //List<int>
            foreach(object obj in (System.Collections.IEnumerable)intList)
                Console.WriteLine(obj);

            //List<string>
            foreach(object obj in (System.Collections.IEnumerable)strList)
                Console.WriteLine(obj);
        }

        static object MakeList(Type t, params object[] items)
        {
            Type type = typeof(List<>).MakeGenericType(t);

            object list = Activator.CreateInstance(type);
            System.Collections.IList ilist = list as System.Collections.IList;
            foreach (object o in items)
                ilist.Add(o);
            return list;
        }

 

 

第二种:

 

 


    public class Main<T> where T: new()
    {
        public void work()
        {
            T t = new T();
            //string s = t.GetName();
        }
    }
//调用
Main<A> m = new Main<A>();
m.work();

泛型,动态创建List<T> (转摘),布布扣,bubuko.com

泛型,动态创建List<T> (转摘)

原文:http://www.cnblogs.com/coolsundy/p/3775800.html

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