C# 泛型數(shù)組學(xué)習(xí)小結(jié)
C# 泛型和數(shù)組在 C# 2.0 中,下限為零的一維數(shù)組自動實現(xiàn) IList<T>。這使您可以創(chuàng)建能夠使用相同代碼循環(huán)訪問數(shù)組和其他集合類型的泛型方法。此技術(shù)主要對讀取集合中的數(shù)據(jù)很有用。IList<T> 接口不能用于在數(shù)組中添加或移除元素;如果試圖在此上下文中調(diào)用 IList<T> 方法(如數(shù)組的 RemoveAt),將引發(fā)異常。下面的代碼示例演示帶有 IList<T> 輸入?yún)?shù)的單個泛型方法如何同時循環(huán)訪問列表和數(shù)組,本例中為整數(shù)數(shù)組。
C# 泛型和數(shù)組代碼
- 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)
- {
- foreach (T item in coll)
- {
- System.Console.Write(item.ToString() + " ");
- }
- System.Console.WriteLine();
- }
- }
C# 泛型和數(shù)組應(yīng)用時注意
盡管 ProcessItems 方法無法添加或移除項,但對于 ProcessItems 內(nèi)部的 T[],IsReadOnly 屬性返回 False,因為該數(shù)組本身未聲明 ReadOnly 特性。
C# 泛型和數(shù)組的相關(guān)內(nèi)容就向你介紹到這里,希望對你了解和學(xué)習(xí)C# 泛型和數(shù)組有所幫助。
【編輯推薦】