範例架構
DataItem:單一資料項(Text/Value)。
DataItemCollection:內部用 ArrayList 管理項目,實作索引器提供 collection[index] 存取。
DataRow:擁有一個 DataItemCollection 屬性。
完整程式碼
using System;
using System.Collections;
public class Program
{
public static void Main()
{
DataRow row = new DataRow();
row.DataItems.Add(new DataItem("Text", "Value"));
Console.WriteLine(row.DataItems[0].Text); // 透過索引器讀取
}
}
public class DataRow
{
public DataItemCollection DataItems { get; } = new DataItemCollection();
}
public class DataItem
{
private string _text, _value;
public DataItem(string text, string value) { _text = text; _value = value; }
public string Text { get => _text; set => _text = value; }
public string Value { get => _value; set => _value = value; }
}
public class DataItemCollection
{
private readonly ArrayList _list = new ArrayList();
public int Count => _list.Count;
// 索引器:支援 collection[index] 讀寫
public DataItem this[int index]
{
get
{
if (index >= 0 && index < _list.Count)
return (DataItem)_list[index];
throw new IndexOutOfRangeException("索引超出範圍");
}
set
{
if (index >= 0 && index < _list.Count)
_list[index] = value;
else
throw new IndexOutOfRangeException("索引超出範圍");
}
}
public void Add(DataItem item) => _list.Add(item);
public void Remove(DataItem item) => _list.Remove(item);
public void RemoveAt(int index) => _list.RemoveAt(index);
}
關鍵點解析
- 索引器宣告:
public DataItem this[int index],回傳型別為 DataItem。
- get 存取子:檢查邊界,合法則回傳
_list[index](需轉型),否則拋例外。
- set 存取子:同樣檢查邊界,合法則指派
value 到陣列位置。
- 用戶端呼叫:
row.DataItems[0].Text 先觸發集合的 get 取得 DataItem,再存取其 Text 屬性。
- 輔助方法:
Add/Remove/RemoveAt 封裝 ArrayList 操作,隱藏內部實作。
現代化改良建議
- 使用
List<DataItem> 取代 ArrayList,獲得型別安全與效能。
- 實作
IEnumerable<DataItem>、ICollection<DataItem> 介面,支援 foreach 與 LINQ。
- 索引器可加
readonly 修飾詞 (C# 8.0+) 表示不修改狀態。