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

相关文章:

  • 2022-12-23
  • 2021-10-28
  • 2021-09-25
  • 2022-01-01
  • 2022-01-13
  • 2021-07-14
猜你喜欢
  • 2021-12-26
  • 2021-12-02
  • 2022-12-23
  • 2022-12-23
  • 2021-11-09
  • 2021-10-02
  • 2021-11-10
相关资源
相似解决方案