C# 泛型数组

来源:互联网 发布:apache index.html 编辑:程序博客网 时间:2024/05/16 10:36

http://www.jb51.net/article/31363.htm

 

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


class Program 

static void Main() 

int[] arr = { 0, 1, 2, 3, 4 }; 
List<int> list = new List<int>(); 
for (int x = 5; x < 10; x++) 

list.Add(x); 

ProcessItems<int>(arr); 
ProcessItems<int>(list); 

static void ProcessItems<T>(IList<T> coll) 

foreach (T item in coll) 

System.Console.Write(item.ToString() + " "); 

System.Console.WriteLine(); 



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

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

0 0