關鍵字 this 指的是該類別目前的實例。 它同時也作為擴展方法第一個參數的修飾符。
備註
本文討論如何用 來 this 指稱當前成員中的接收者實例。 如需其在擴充方法中使用的詳細資訊,請參閱 extension 關鍵詞。
C# 語言參考資料記錄了 C# 語言最新版本。 同時也包含即將推出語言版本公開預覽功能的初步文件。
文件中標示了語言最近三個版本或目前公開預覽版中首次引入的任何功能。
小提示
欲查詢某功能何時首次在 C# 中引入,請參閱 C# 語言版本歷史的條目。
常見的 this 用途包括:
以相似名稱隱藏的合格會員,例如:
public class Employee { private string alias; private string name; public Employee(string name, string alias) { // Use this to qualify the members of the class // instead of the constructor parameters. this.name = name; this.alias = alias; } }將物件作為參數傳遞給其他方法。
CalcTax(this);宣告 索引器,例如:
public int this[int param] { get => array[param]; set => array[param] = value; }
靜態成員函式存在於類別層級,而非物件的一部分。 他們沒有 this 指標。 用靜態方法指代 是 this 錯誤。
在以下範例中,參數 name 和 alias 隱藏了名稱相同的欄位。 關鍵詞會將 this 這些變數限定為 Employee 類別成員。 關鍵詞 this 也會指定 屬於另一個類別之 方法 CalcTax的物件。
class Employee
{
private string name;
private string alias;
// Constructor:
public Employee(string name, string alias)
{
// Use this to qualify the fields, name and alias:
this.name = name;
this.alias = alias;
}
// Printing method:
public void printEmployee()
{
Console.WriteLine($"""
Name: {name}
Alias: {alias}
""");
// Passing the object to the CalcTax method by using this:
Console.WriteLine($"Taxes: {Tax.CalcTax(this):C}");
}
public decimal Salary { get; } = 3000.00m;
}
class Tax
{
public static decimal CalcTax(Employee E)=> 0.08m * E.Salary;
}
class Program
{
static void Main()
{
// Create objects:
Employee E1 = new Employee("Mingda Pan", "mpan");
// Display results:
E1.printEmployee();
}
}
/*
Output:
Name: Mingda Pan
Alias: mpan
Taxes: $240.00
*/
C# 語言規格
如需詳細資訊,請參閱 C# 語言規格。 語言規格是 C# 語法和使用方式的最終來源。