this (C# 參考)this (C# Reference)

this 關鍵字指的是類別的目前執行個體,也用作擴充方法第一個參數的修飾詞。The this keyword refers to the current instance of the class and is also used as a modifier of the first parameter of an extension method.

注意

本文討論如何搭配使用 this 與類別執行個體。This article discusses the use of this with class instances. 如需其在擴充方法中之用法的詳細資訊,請參閱擴充方法For more information about its use in extension methods, see Extension Methods.

下列是 this 的常見用法:The following are common uses of this:

  • 限定透過類似名稱所隱藏的成員,例如︰To qualify members hidden by similar names, for example:

    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;
        }
    }
    
  • 傳遞物件作為其他方法的參數,例如:To pass an object as a parameter to other methods, for example:

    CalcTax(this);
    
  • 宣告索引子,例如︰To declare indexers, for example:

    public int this[int param]
    {
        get { return array[param]; }
        set { array[param] = value; }
    }
    

靜態成員函式存在於類別層級,而不是物件的一部分,因此沒有 this 指標。Static member functions, because they exist at the class level and not as part of an object, do not have a this pointer. 在靜態方法中參照 this 會產生錯誤。It is an error to refer to this in a static method.

範例Example

在此範例中,this 是用來限定 Employee 類別成員 namealias,而這些是透過類似的名稱進行隱藏。In this example, this is used to qualify the Employee class members, name and alias, which are hidden by similar names. 它也會用來將物件傳遞給屬於另一個類別的 CalcTax 方法。It is also used to pass an object to the method CalcTax, which belongs to another class.

class Employee
{
    private string name;
    private string alias;
    private decimal salary = 3000.00m;

    // 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: {0}\nAlias: {1}", name, alias);
        // Passing the object to the CalcTax method by using this:
        Console.WriteLine("Taxes: {0:C}", Tax.CalcTax(this));
    }

    public decimal Salary
    {
        get { return salary; }
    }
}

class Tax
{
    public static decimal CalcTax(Employee E)
    {
        return 0.08m * E.Salary;
    }
}

class MainClass
{
    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# language specification

如需詳細資訊,請參閱<C# 語言規格>。For more information, see the C# Language Specification. 語言規格是 C# 語法及用法的限定來源。The language specification is the definitive source for C# syntax and usage.

另請參閱See also