| 場景 | 語法 | 說明 |
|---|---|---|
| 消除名稱衝突 | this.field = param; | 建構函式/方法參數與欄位同名時 |
| 建構函式鏈結 | this(...) | 避免重複初始化邏輯 |
| 索引子定義 | public T this[int i] { get; set; } | 讓類別支援陣列式存取 |
| 傳遞自身參考 | Other.Method(this); | 雙向關聯、Visitor 模式、流式介面 |
using System;
class Temperature {
private double _celsius;
private string _cache;
public double Celsius {
get => _celsius;
private set => _celsius = value;
}
// 1. 消除衝突
public Temperature(double celsius) {
this._celsius = celsius; // 參數 celsius vs 欄位 _celsius
}
// 2. 複本建構函式 + 自身比較
public Temperature(Temperature other) {
if (this != other) { // 3. 判斷是否為同一實例
_celsius = other.Celsius;
}
}
// 4. 傳遞自身給轉換器
public override string ToString() =>
$"{_celsius}°C = {Converter.ToFahrenheit(this)}°F";
// 5. 效能測試:this. 欄位 vs 直接欄位
public string TestWithThis() {
long start = Environment.TickCount;
for (int i = 0; i < 10_000_000; i++) this._cache = i.ToString();
return $"With this: {Environment.TickCount - start} ms";
}
public string TestWithoutThis() {
long start = Environment.TickCount;
for (int i = 0; i < 10_000_000; i++) _cache = i.ToString();
return $"Without this: {Environment.TickCount - start} ms";
}
}
static class Converter {
public static double ToFahrenheit(Temperature t) => 1.8 * t.Celsius + 32;
}
class Program {
static void Main() {
Temperature t = new Temperature(37.5);
Console.WriteLine(t); // 37.5°C = 99.5°F
Console.WriteLine(t.TestWithThis()); // ~4375 ms
Console.WriteLine(t.TestWithoutThis()); // ~4406 ms (差異可忽略)
Console.ReadKey();
}
}
this = other、this++ 等修改
struct Point {
public int X, Y;
public void Reset() {
// 結構體方法中 this 為值型別參考(ref)
this = new Point(); // 等同 X=0; Y=0;
}
public void Translate(int dx, int dy) {
this = new Point(X + dx, Y + dy); // 重新指派整個結構體
}
}
範例中 TestWithThis vs TestWithoutThis 差異 < 1%,屬於雜訊範圍。JIT 編譯器會最佳化掉 this. 前綴。結論:可讀性優先,無需為 this. 效能擔憂。
class QueryBuilder {
private string _table, _where;
public QueryBuilder From(string table) { _table = table; return this; }
public QueryBuilder Where(string condition) { _where = condition; return this; }
public string Build() => $"SELECT * FROM {_table} WHERE {_where};";
}
// 用法
var sql = new QueryBuilder().From("Users").Where("Age > 18").Build();
回傳 this 實現方法鏈結,廣泛用於建構器、LINQ、設定物件。