C# this[int index] 語法讓物件支援陣列存取語法,內部封裝 get/set 邏輯:
public class Skyscraper {
private Story[] stories;
public Story this[int index] {
get => stories[index];
set { if (value != null) stories[index] = value; }
}
}
var building = new Skyscraper(...);
building[102] = new Story("The Top One", ...); // 直觀語法
Java 需呼叫 getStory(102)/setStory(102, ...),較冗長。
本質:封裝方法簽名的物件,可參考多個方法 (多播),支援實例/靜態方法。
this核心應用:**事件處理** (見下篇)。Anders Hejlsberg 設計委派意在「取代指標」,中文譯「指代」更貼切 (取代+代理)。