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

第一种:

 

       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();

posted @ 2014-06-08 09:56  coolsundy  阅读(2610)  评论(0编辑  收藏  举报