作者knifehandz (手刀)
看板C_Sharp
標題Re: [問題] List<T> 觀念問題
時間Sat Nov 5 05:53:41 2011
這有點歷史問題...
先說明 IList 是個介面 (Interface),所以不算繼承,只算實作。
最原始的 List 其實叫做 ArrayList,從 .NET 1.0 就有了,是在 System.Collections
裡面;那時的 ArrayList 其實就是一個只能容納 object 的類別,模仿取代 C 時代
的指標 list 而已。
現在用的 System.Collections.Generic 中的 List 其實是有 generics 後的版本,
可以指定該 List 的資料型別,用於取代原本只能使用 object 的 ArrayList。
但是原型上這兩個是應該通用的,所以說 List 必須繼承 IList,以便有使用到 IList
介面宣告時可以相容新的 List。
原 PO 所說的 Add(object item),其實就是 IList 的實作,如果不想處理相關的新增
動作,直接 throw new NotImplementedException("Non-generic list not supported")
就好,但如果要實作則建議做型別判斷,如:
public int Add(object item) {
if (item is int) {
// 對 int 做轉換動作
} else if (...) {
} else {
throw new NotSupportedException("Data type not supported.");
}
}
(上例為 c#)
正確使用上如果有人使用你繼承 List 的類別,名為 MyInheritedList,宣告為
public class MyInheritedList : IList<int>, IList, ... (後面省略)
他可以這樣用:
IList myList = new MyInheritedList();
myList.Add(12345);
而不會出現錯誤
或是他也可以這樣用:
IList<int> myList = new MyInheritedList();
myList.Add(12345);
當然也可以用其他型別/類別解釋,不過大同小異 - 會要求有 Add(object item) 純粹
是歷史問題。
附上 MSDN 做參考:
List<T> -
http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx
ArrayList -
http://msdn.microsoft.com/en-us/library/system.collections.arraylist.aspx
IList.Add 方法 -
http://msdn.microsoft.com/en-us/library/system.collections.ilist.add.aspx
小弟第一次回應文,還請各位先進多多指正,謝謝!
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 124.120.81.102
推 party100046:List<T> 用在動態新增也可以唷 11/05 19:29
→ knifehandz:嗯,ArrayList 跟 List 最大用處其實就是動態陣列 11/06 04:29