第一個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();
}
}
}