星空网 > 软件开发 > ASP.net

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

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




原标题:为什么说泛型是类型安全的

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流