索引子讓類別實例支援 obj[index] 語法,本質是含參數的屬性。與陣列不同:
int(可為 string、Tuple、enum 等)get/set 存取層級
using System;
class Point {
public double X, Y;
public Point(double x, double y) { X = x; Y = y; }
public override string ToString() => $"X: {X}, Y: {Y}";
}
class Points {
private readonly Point[] _points;
public Points(Point[] points) => _points = points;
public int Count => _points.Length;
// 整數索引子
public Point this[int index] {
get => _points[index];
set => _points[index] = value;
}
}
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() {
// Points 範例
Point[] pts = new Point[10];
for (int i = 0; i < pts.Length; i++) pts[i] = new Point(i, Math.Sin(i));
Points ps = new Points(pts);
for (int i = 0; i < ps.Count; i++) Console.WriteLine(ps[i]);
// Weather 範例
WeatherOfWeek w = new WeatherOfWeek();
for (int i = 0; i < 6; i++) Console.WriteLine(w[i]);
foreach (var d in new[] { "Sunday", "Monday", "Friday", "Saturday" })
Console.WriteLine(w[d]);
Console.ReadKey();
}
}
| 特性 | 語法範例 | 應用場景 |
|---|---|---|
| 多參數 | public double this[int r, int c] | 矩陣、影像像素、棋盤 |
| 多載 | this[int i] + this[string key] | 雙模式存取(如 DataRow) |
| 介面定義 | interface IMatrix { double this[int r, int c] { get; set; } } | 抽象矩陣運算 |
| 存取修飾 | public string this[int i] { get; private set; } | 唯讀對外、內部可寫 |
| 靜態索引子 | ❌ C# 不支援 | 改用靜態方法 Get(key) |
class AppSettings {
private readonly Dictionary _data = new();
public string this[string key] {
get => _data.TryGetValue(key, out var v) ? v : null;
set => _data[key] = value;
}
}
readonly struct Matrix {
private readonly double[,] _data;
public Matrix(int rows, int cols) => _data = new double[rows, cols];
public double this[int r, int c] {
get => _data[r, c];
set => _data[r, c] = value;
}
public int Rows => _data.GetLength(0);
public int Cols => _data.GetLength(1);
}
class Points : IEnumerable {
private readonly Point[] _points;
public Point this[int i] => _points[i];
public int Count => _points.Length;
public IEnumerator GetEnumerator() => ((IEnumerable)_points).GetEnumerator();
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
}
ArgumentOutOfRangeException,null 拋 ArgumentNullExceptionCount/Length 配合迴圈IEnumerable<T> 支援 LINQ 與 foreachreadonly struct + Span<T> 避免複製