在 C# 程式設計中,this 關鍵字是開發者每天都會遇到、卻常被忽視的基石之一。它不僅代表目前類別的實例參考,更在建構子鏈結與索引子定義中扮演關鍵角色。本文將透過實戰範例,系統性拆解 this 的三大核心應用場景,助你寫出更清晰、更具擴充性的程式碼。
這是 this 最基礎也最常見的用途。當區域變數或參數名稱與類別欄位(Field/Property)重疊時,this 能明確區分「誰屬於物件、誰屬於方法區域」。雖然在無歧義情況下可省略,但保留它能提升程式碼可讀性,尤其在團隊協作或大型專案中。
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string name, int age)
{
// 明確指派:this.Name 指向屬性,name 指向參數
this.Name = name;
this.Age = age;
}
}
技巧提示: 現代 C# 慣用命名慣例(如參數用 camelCase、屬性用 PascalCase)往往能避免命名衝突,但 this 在繼承鏈中存取基類被隱藏成員時,依然不可或缺。
this(...) 呼叫另一個建構子透過 this(參數列表) 語法,可在建構子之間建立呼叫關係,實現「邏輯集中、參數預設」的設計模式。這能避免重複初始化程式碼,確保物件建立流程一致性。
public class SuperHero
{
public int Age { get; private set; }
public string Name { get; private set; }
// 核心建構子:包含完整初始化邏輯
public SuperHero(int age, string name)
{
Age = age;
Name = name;
Console.WriteLine($"我是叫 {Name} 的超人,年齡 {Age}");
}
// 僅指定年齡,姓名使用預設值
public SuperHero(int age) : this(age, "無名英雄")
{
Console.WriteLine("超人的年齡 {0}", age);
}
// 無參數建構子,完全使用預設值
public SuperHero() : this(100)
{
Console.WriteLine("我是超人!");
}
}
var hero = new SuperHero(10, "強子");
輸出結果:
超人的年齡 100
我是叫 強子 的超人,年齡 10
關鍵觀察: 建構子鏈結會由最底層(參數最多者)向上依序執行,this() 必須置於建構子簽名之後、大括號之前,且每個建構子只能呼叫一個 this()。
索引子讓類別實例能像陣列或集合一樣,透過 obj[index] 語法直接存取內部資料。this 在此處不是關鍵字,而是索引子的「名稱」——因為索引子不允許自訂名稱,故統一使用 this 代表「目前實例的索引存取器」。
public class NameCollection
{
private readonly string[] _names = new string[10];
// 索引子定義:this[int index]
public string this[int index]
{
get => _names[index];
set => _names[index] = value;
}
}
var collection = new NameCollection();
collection[0] = "Hello";
collection[1] = "World";
Console.WriteLine(collection[0]); // 輸出:Hello
進階應用: 索引子支援多參數(如 this[int row, int col])與不同型別索引鍵(如 this[string key]),廣泛用於矩陣運算、快取容器、動態資料綁定等場景。
掌握 this 的三重身分,不僅能寫出更專業的 C# 程式碼,更能在閱讀框架原始碼(如 ASP.NET Core、Entity Framework)時,快速理解其設計意圖。