this 僅限於建構函式、類別方法、結構方法、結構建構函式中使用,表示當前實例的參考。
| 情境 | 型別分類 | 含義 |
|---|---|---|
| 類別建構函式 | 值型別 | 正在建構的物件參考 |
| 類別方法 | 值型別 | 呼叫該方法的物件參考 |
| 結構建構函式 | 變數型別 | 正在建構的結構參考 |
| 結構方法 | 變數型別 | 呼叫該方法的結構參考 |
class A {
public int X;
public void Main() {
X = 5;
Console.WriteLine($"X={X}, this.X={this.X}"); // 相同
}
}
this++、this-- 非法;但可作為回傳值。this->、::,C# 僅用 . 存取成員。
// 階乘驗證
class Fact {
int x;
public int GetFact() {
int save = x, a = 1;
while (x > a) { a++; float t = this.x / a; x /= a; if ((float)x != t) return -1; }
Swap(ref this.x, ref save); return save;
}
}
// 視窗啟用追蹤
class Window {
public Window[] Child = new Window[5];
public bool HasChild, IsActive;
public Window GetActiveWindow() {
if (!HasChild) { IsActive = true; return this; }
for (int i=0;i<5;i++) if (Child[i].IsActive) return Child[i];
return this;
}
}