泛型的好处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();
        }
    }

 

转载于:https://www.cnblogs.com/binyao/archive/2013/04/25/3043646.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值