首页 > 其他 > 详细

为什么说泛型是类型安全的

时间:2015-04-04 07:58:38      阅读:310      评论:0      收藏:0      [点我收藏+]

通常说泛型,比如List<T>是类型安全的,为什么这么说呢?

 

先来看一个类型不安全的例子。

 

    class Program
    {
        static void Main(string[] args)
        {
            var tempArr = new ArrayList();
            tempArr.Add(1);
            tempArr.Add("2");
            foreach (var item in tempArr)
            {
                int tempInt = (int) item;
                Console.WriteLine(tempInt);
            }
            Console.ReadKey();
        }
    }

 

可以往ArrrayList实例中添加任何类型。但在遍历集合转换的时候,会抛出一个转换异常。

 

技术分享

 

如果使用List<T>泛型呢?

 

    class Program
    {
        static void Main(string[] args)
        {
            List<int> tempArr = new List<int>();
            tempArr.Add(1);
            tempArr.Add(2);
            foreach (var item in tempArr)
            {
                int tempInt = (int) item;
                Console.WriteLine(tempInt);
            }
            Console.ReadKey();
        }
    }

 

用List<int>后,关于类型安全,有2个体会:

 

1、如果使用tempArr.Add("3"),这在编译期就不通过
2、在进行类型转换的时候不会抛出异常

为什么说泛型是类型安全的

原文:http://www.cnblogs.com/darrenji/p/4391524.html

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