基本語法與整數索引子
using System;
class MyClass {
private float[] fs = new float[3] { 1.1f, 2.2f, 3.3f };
// 一般屬性
public int Length {
get { return fs.Length; }
set { fs = new float[value]; }
}
// 索引子:this[int n]
public float this[int n] {
get { return fs[n]; }
set { fs[n] = value; }
}
}
class Program {
static void Main() {
MyClass obj = new MyClass();
for (int i = 0; i < obj.Length; i++) Console.WriteLine(obj[i]); // 1.1, 2.2, 3.3
for (int i = 0; i < obj.Length; i++) obj[i] += 5.5f;
for (int i = 0; i < obj.Length; i++) Console.WriteLine(obj[i]); // 6.6, 7.7, 8.8
obj.Length = 5; // 觸發 set,重新配置陣列
for (int i = 0; i < obj.Length; i++) Console.WriteLine(obj[i]); // 0, 0, 0, 0, 0
Console.ReadKey();
}
}
多型索引子:字串、多維、複合鍵
using System;
class WeatherOfWeek {
// 整數索引:0=Sun, 5=Fri
public string this[int index] {
get {
switch (index) {
case 0: return "Today is cloudy!";
case 5: return "Today is thundershower!";
default: return "Today is fine!";
}
}
}
// 字串索引:曜日名稱
public string this[string day] {
get {
switch (day) {
case "Sunday": return "Today is cloudy!";
case "Friday": return "Today is thundershower!";
default: return "Today is fine!";
}
}
}
}
class Program {
static void Main() {
var w = new WeatherOfWeek();
for (int i = 0; i < 6; i++) Console.WriteLine(w[i]);
foreach (var d in new[] { "Sunday", "Monday", "Friday" })
Console.WriteLine(w[d]);
Console.ReadKey();
}
}
索引子進階特性
| 特性 | 說明 |
| 多參數 | public T this[int x, int y] 適用矩陣、棋盤、圖像像素 |
| 多載 | 同類別可定義多個索引子,參數型別/數量不同 |
| 存取修飾詞 | get/set 可個別加 protected/private |
| 介面定義 | interface IMatrix { double this[int r, int c] { get; set; } } |
| 靜態索引子 | C# 不支援 static this[],需改用靜態方法 |
實務應用場景
- 自訂集合封裝:
List<T>、Dictionary<K,V> 皆大量使用索引子
- 資料列存取:
DataTable.Rows[i]["ColumnName"]
- 矩陣/圖像處理:
bitmap[x, y]、matrix[row, col]
- 設定/快取查詢:
config["section:key"]、cache[key]
設計建議
- 索引子應表達「存取元素」語意,避免在 get/set 中執行複雜業務邏輯
- 提供
Count/Length 屬性配合迴圈使用
- 參數驗證:越界拋
ArgumentOutOfRangeException,null 拋 ArgumentNullException
- 考慮實作
IEnumerable<T> 支援 foreach