泛型和数组(C# 编程指南)

具有零下限的单维数组会自动实现 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)
    {
        // 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();
    }
}

另请参阅