泛型和陣列 (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();
    }
}

另請參閱