this 代表目前類別的執行個體。三大主要用途:
public class Employee
{
private string _name;
private string _alias;
public Employee(string name, string alias)
{
// 參數 name/alias 隱藏了欄位 _name/_alias
// 使用 this 明確指派給實例欄位
this._name = name;
this._alias = alias;
}
}
public class TaxCalculator
{
public decimal Calculate(Employee emp) { /* ... */ return 0; }
}
public class Employee
{
public void ProcessTax()
{
var calculator = new TaxCalculator();
// 將 this (目前 Employee 實例) 傳遞給計算器
decimal tax = calculator.Calculate(this);
}
}
public class ScoreBoard
{
private int[] _scores = new int[100];
// 索引子:讓類別像陣列一樣被存取
public int this[int index]
{
get => _scores[index];
set => _scores[index] = value;
}
}
// 使用方式
var board = new ScoreBoard();
board[0] = 95; // 呼叫 set
int score = board[0]; // 呼叫 get
public static class StringExtensions
{
// this string str 表示擴充 string 型別
public static bool IsValidEmail(this string str)
{
return System.Text.RegularExpressions.Regex.IsMatch(
str, @"^[^@\s]+@[^@\s]+\.[^@\s]+$");
}
}
// 使用方式:像實例方法一樣呼叫
string email = "test@example.com";
bool valid = email.IsValidEmail(); // 實際呼叫 StringExtensions.IsValidEmail(email)
public class Point
{
public int X { get; set; }
public int Y { get; set; }
public string Label { get; set; }
// 主要建構函式
public Point(int x, int y, string label)
{
X = x; Y = y; Label = label;
}
// 透過 this() 呼叫主要建構函式,避免重複程式碼
public Point(int x, int y) : this(x, y, "Default") { }
public Point() : this(0, 0, "Origin") { }
}
public class Demo
{
public static void StaticMethod()
{
// 錯誤 CS0026:靜態方法中無法使用 this
// Console.WriteLine(this.ToString());
}
public void InstanceMethod()
{
// 正確:實例方法中 this 可用
Console.WriteLine(this.GetType().Name);
}
}
| 特性 | this | base |
|---|---|---|
| 指向對象 | 目前實例 | 基底類別實例部分 |
| 建構函式呼叫 | this(...) 同類別其他建構函式 | base(...) 基底類別建構函式 |
| 成員存取 | 目前類別成員(含隱藏基底的) | 基底類別成員(穿透隱藏) |
| 靜態方法 | 禁止 | 禁止 |
| 索引子 | 定義索引子語法 | 無 |
| 擴充方法 | 第一個參數修飾詞 | 無 |
_name)而非依賴 this.name,提升可讀性using 才生效,設計時考慮可發現性this() 呼叫