共用方式為


這個關鍵詞

this 關鍵詞是指 類別的目前實例,而且也會當做擴充方法第一個參數的修飾詞使用。

備註

本文討論在類別實例中如何使用 this。 如需其在擴充方法中使用的詳細資訊,請參閱 extension 關鍵詞。

以下是 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 是錯誤的。

在此範例中,參數 namealias 會隱藏具有相同名稱的欄位。 關鍵詞會將 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# 語法和使用方式的最終來源。

另請參閱