C# 1.x 集合皆儲存 object 參考。CollectionBase、ReadOnlyCollectionBase、DictionaryBase 提供抽象基類,可建立型別安全介面包裝非安全集合。C# 2.0 泛型將徹底解決此問題。
public class MyObjectCollection : ArrayList
{
[Obsolete("Please use specify object.", true)]
public override int Add(object value) { return base.Add(value); }
public int Add(MyObject value) { return base.Add(value); }
new public MyObject this[int index]
{
get { return base[index] as MyObject; }
set { base[index] = value; }
}
}
利用 Obsolete 屬性阻止直接呼叫 Add(object),僅暴露強型別 Add(MyObject) 與索引子。本質仍非型別安全,但可攔截大多數誤用。
類別包含集合時,應實作索引子與 IEnumerable:
// 多維索引子
public int this[int x, int y] { get { return ComputeValue(x, y); } }
// IEnumerable 介面
public interface IEnumerable { IEnumerator GetEnumerator(); }
public interface IEnumerator { object Current { get; } bool MoveNext(); void Reset(); }
若模型為陣列,考慮實作 IList、ICollection;若為字典,實作 IDictionary。最簡單做法:繼承 CollectionBase 或 DictionaryBase。
IEnumerable。