泛型和数组(C# 编程)

来源:互联网 发布:凡人修仙传优化补丁 编辑:程序博客网 时间:2024/06/05 03:46

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

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)    {        // IsReadOnly returns True for the array and False for the List.        System.Console.WriteLine            ("IsReadOnly returns {0} for this collection.",            coll.IsReadOnly);        // The following statement causes a run-time exception for the         // array, but not for the List.        //coll.RemoveAt(4);        foreach (T item in coll)        {            System.Console.Write(item.ToString() + " ");        }        System.Console.WriteLine();    }}

原文链接:http://blog.csdn.net/u013108312/article/details/52051216

0 0