下限が 0 の 1 次元配列では、 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();
}
}
こちらも参照ください
GitHub で Microsoft と共同作業する
このコンテンツのソースは GitHub にあります。そこで、issue や pull request を作成および確認することもできます。 詳細については、共同作成者ガイドを参照してください。
.NET