泛型的好处1

工作中一直使用泛型,但突然想想,为什么要使用泛型,还真说不出个二三四来,所以看看书,总结一下!

Array 比如数组,继承自System.Array

ArrayList Collection对象, 继承自System.Collections.

List<T> 泛型, 继承自System.Collections.

使用泛型的好处

1. 使用泛型最大限度的重用代码,保护类型的安全以及提高效率。(使用参数T, 大大简化类型之间的强制转换或装箱操作的过程)

2. 使用泛型可以创建集合类。

3. 使用泛型类型可以创建自己的泛型接口,泛型方法,泛型类,泛型事件和泛型委托。

4. 使用泛型类型可以对泛型类型进行约束,以访问特定数据类型的方法。

5. 关于泛型数据类型中使用的类型的信息,可以运行时通过反射获得

View Code
public class TPlant
    {
        protected string name;
        public TPlant(string name)
        {
            this.name = name;

        }

        public void OutPrint()
        {

            Console.WriteLine("{0}是一个泛型娃", name);
        }
    }
    public class Program
    {
        static void Main(string[] args)
        {
            //定义一个泛型List 集合
            List<TPlant> TPlantCollection = new List<TPlant>();

            //向集合添加对象
            TPlantCollection.Add(new TPlant("Binyao"));
            TPlantCollection.Add(new TPlant("Antony"));

            //遍历泛型
            foreach (var plant in TPlantCollection)
            {
                //调用TPlant对象中的OutPrint()方法输出结果
                plant.OutPrint();
            }

            Console.ReadLine();
        }
    }

 

posted @ 2013-04-25 22:11  Binyao  阅读(333)  评论(0编辑  收藏  举报