public void Add(Card newCard) { List.Add(newCard); }
public void Remove(Card newCard) { List.Remove(newCard); }
疑問:List 非靜態,為什麼直接用 List.Add 而非 this.List.Add?
List 是 CollectionBase 的受保護實例屬性,返回 IList 類型,封裝了內部 ArrayList。
// CollectionBase 簡化源碼 (參考 MSDN)
public abstract class CollectionBase : IList, ICollection, IEnumerable {
protected ArrayList InnerList { get; } = new ArrayList();
protected IList List { get { return InnerList; } } // 非靜態實例屬性
// ... 實現 IList 接口方法委託給 InnerList ...
}
List.Add?Cards 的實例方法中,List 等價於 this.Listthis 隱式可訪問基類受保護成員List 返回 IList,調用其 Add 方法List 屬性:獲取一個
IList,它包含CollectionBase實例中元素的列表。
using System.Collections;
public class Card { public string Name; }
public class Cards : CollectionBase {
public void Add(Card card) { List.Add(card); } // 等同 this.List.Add(card)
public void Remove(Card card) { List.Remove(card); }
public Card this[int index] {
get { return (Card)List[index]; }
set { List[index] = value; }
}
public void CopyTo(Cards target) {
for (int i = 0; i < Count; i++) target[i] = this[i];
}
public bool Contains(Card card) { return InnerList.Contains(card); }
}
| 屬性 | 類型 | 訪問權限 | 用途 |
|---|---|---|---|
InnerList | ArrayList | protected | 直接訪問底層 ArrayList |
List | IList | protected | 通過接口訪問,封裝性更好 |
Count | int | public | 元素數量 |
Capacity | int | public | 內部容量 |
List 是實例屬性而非靜態屬性。在派生類方法中直接訪問 List 即訪問 this.List,這是 C# 基類成員訪問的基本語法。建議閱讀 MSDN 官方文檔 獲取權威定義。