this(C# 參考)

來源:互聯網
上載者:User

標籤:執行個體   cti   聲明   地址   which   div   pointer   用途   gui   

原文地址:https://msdn.microsoft.com/zh-cn/library/dk1507sz.aspx

this 關鍵字引用類的當前執行個體,還可用作擴充方法的第一個參數的修飾符。

注意

本文討論對類執行個體使用 this。 有關其在擴充方法中使用的更多資訊,請參見擴充方法(C# 編程指南)。

以下是 this 的常用用途:

  • 限定被相似的名稱隱藏的成員,例如:

C# 
public Employee(string name, string alias){    // Use this to qualify the fields, name and alias:    this.name = name;    this.alias = alias;}
  • 將對象作為參數傳遞到其他方法,例如:

      
    CalcTax(this);
  • 聲明索引器,例如:

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

由於靜態成員函數存在於類一級,並且不是對象的一部分,因此沒有 this 指標。 在靜態方法中引用 this 是錯誤的。

樣本

在本例中,this 用於限定 Employee 類成員 name 和 alias,它們都被相似的名稱隱藏。 該關鍵字還用於將對象傳遞到屬於其他類的方法 CalcTax。

C# 
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 */

 

this(C# 參考)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.