C#中This的用法

來源:互聯網
上載者:User

第一個this的意思是調用Car(int petals)方法的屬性petals。
第二個this的意思是執行個體化Car(String s, int petals)方法中的參數s(this.s = s)。
第三個this是調用Car(String s, int petals)方法的兩個參數並傳參。

在C#中,this關鍵字代表當前執行個體,我們可以用this.來調用當前執行個體的成員方法,變數,屬性,欄位等;
也可以用this來做為參數狀當前執行個體做為參數傳入方法.
還可以通過this[]來聲明索引器

下面是你這段程式的註解:
using System;              // 引入使命空間System
namespace CallConstructor // 聲明命名空間CallConstructor
{
public class Car           // 聲明類Car
{
int petalCount = 0;        //在Car類中聲明一個非靜態整型變數petalCount,初始值為0
              未用Static聲明的變數叫做靜態變數,非靜態成員屬類的執行個體,我們只能在調用類的構
              造函數對類進行執行個體化後才能通過所得的執行個體加"."來訪問聲明一個非靜態字串變數s,                  
              初始值為"null"; 注意:s = "null"與s = null是不同的                                                                                            
String s = "null";
Car(int petals)          // Car類的預設建構函式
{
petalCount = petals;    // Car類的預設建構函式中為 petalCount 賦值為傳入的參數petals的值
Console.WriteLine("Constructor w/int arg only,petalCount = " + petalCount);  // 輸出petalCount
}
Car(String s, int petals)// 重載Car類的建構函式 Car(String s, int petals)的第二個參數
: this(petals)         // : this(petals) 表示從當前類中調用petals變數的值來作為建構函式重載方法
{
this.s = s;
Console.WriteLine("String & int args");
}
// 在建構函式中為s賦值
// 非靜態成員可以在建構函式或非靜態方法中使用this.來調用或訪問,也可以直接打變數的名字,因此這一句等效於s = s,
//但是這時你會發類的變數s與傳入的參數s同名,這裡會造成二定義,所以要加個this.表示等號左邊的s是當前類自己的變數
Car()         // 重載建構函式,:
: this("hi", 47) // this("hi", 47) 表示調Car(String s, int petals) 這個重載的建構函式,並直接傳入變數"hi"和47
{
Console.WriteLine("default constructor");
}
public static void Main()
{
Car x = new Car();
Console.Read();
}
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.