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


通常说泛型,比如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实例中添加任何类型。但在遍历集合转换的时候,会抛出一个转换异常。

 

1

 

如果使用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、在进行类型转换的时候不会抛出异常


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM