陣列作為 IEnumerable 例項

所有陣列都實現非通用的 IList 介面(因此非通用的 ICollectionIEnumerable 基介面)。

更重要的是,一維陣列實現了 IList<>IReadOnlyList<> 通用介面(及其基介面),用於它們包含的資料型別。這意味著它們可以被視為通用的可列舉型別,並傳遞給各種方法,而無需先將它們轉換為非陣列形式。

int[] arr1 = { 3, 5, 7 };
IEnumerable<int> enumerableIntegers = arr1; //Allowed because arrays implement IEnumerable<T>
List<int> listOfIntegers = new List<int>();
listOfIntegers.AddRange(arr1); //You can pass in a reference to an array to populate a List.

執行此程式碼後,列表 listOfIntegers 將包含一個包含值 3,5 和 7 的 List<int>

IEnumerable<> 支援意味著可以使用 LINQ 查詢陣列,例如 arr1.Select(i => 10 * i)