C# 泛型数组学习小结

C# 泛型和数组在 C# 2.0 中,下限为零的一维数组自动实现 IList<T>。这使您可以创建能够使用相同代码循环访问数组和其他集合类型的泛型方法。此技术主要对读取集合中的数据很有用。IList<T> 接口不能用于在数组中添加或移除元素;如果试图在此上下文中调用 IList<T> 方法(如数组的 RemoveAt),将引发异常。下面的代码示例演示带有 IList<T> 输入参数的单个泛型方法如何同时循环访问列表和数组,本例中为整数数组。

C# 泛型和数组代码

 
 
 
  1. class Program  
  2. {  
  3.     static void Main()  
  4.     {  
  5.         int[] arr = { 0, 1, 2, 3, 4 };  
  6.         List<int> list = new List<int>();  
  7.  
  8.         for (int x = 5; x < 10; x++)  
  9.         {  
  10.             list.Add(x);  
  11.         }  
  12.  
  13.         ProcessItems<int>(arr);  
  14.         ProcessItems<int>(list);  
  15.     }  
  16.  
  17.     static void ProcessItems<T>(IList<T> coll)  
  18.     {  
  19.         foreach (T item in coll)  
  20.         {  
  21.             System.Console.Write(item.ToString() + " ");  
  22.         }  
  23.         System.Console.WriteLine();  
  24.     }  
  25. }  

C# 泛型和数组应用时注意

尽管 ProcessItems 方法无法添加或移除项,但对于 ProcessItems 内部的 T[],IsReadOnly 属性返回 False,因为该数组本身未声明 ReadOnly 特性。

C# 泛型和数组的相关内容就向你介绍到这里,希望对你了解和学习C# 泛型和数组有所帮助。

【编辑推荐】

  1. C# 泛型的优点浅谈
  2. C# 泛型类型参数浅析
  3. C# 类型参数约束分析及应用浅析
  4. C# 泛型接口应用浅析
  5. C# 泛型方法概念及使用浅析
THE END