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


    通常说泛型,比如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、在进行类型转换的时候不会抛出异常

  • 相关阅读:
    Spring Boot 学习随记
    Prometheus 普罗米修斯监控
    安装VC++6.0步骤及心得
    NFS 系统搭建
    Centos 搭建邮箱系统
    搭建 RTMP 服务器
    阿里云 DTS 实践
    ELK 搭建
    Prometheus 和 Grafana 安装部署
    Centos7 Nagios 搭建
  • 原文地址:https://www.cnblogs.com/darrenji/p/4391524.html
Copyright © 2020-2023  润新知