this

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

下面是你這段程序的註解: 
// 引入使命空間System 
using System; 
// 聲明命名空間CallConstructor 
namespace CallConstructor 

// 聲明類Car 
public class Car 

// 在Car類中: 
// 聲明一個非靜態的整型變量petalCount,初始值爲0 
// 未用Static聲明的變量叫做靜態變量,非靜態成員屬於 
類的實例,我們只能在調用類的構造函數對類進行實例化後才能通過所得的實例加"."來訪問 
int petalCount = 0; 
// 聲明一個非靜態的字符串變量s,初始值爲"null"; 
// 注意:s = "null"與s = null是不同的 
String s = "null"; 
// Car類的默認構造函數 
Car(int petals) 

// Car類的默認構造函數中爲 petalCount 賦值爲傳入的參數petals的值 
petalCount = petals; 
// 輸出petalCount 
Console.WriteLine("Constructor w/int arg only,petalCount = " + petalCount); 

// 重載Car類的構造函數 
// : this(petals) 表示從當前類中調用petals變量的值來作爲構造函數重載方法Car(String s, int petals)的第二個參數
Car(String s, int petals) 
: this(petals) 

// 在構造函數中爲s賦值 
// 非靜態成員可以在構造函數或非靜態方法中使用this.來調用或訪問,也可以直接打變量的名字,因此這一句等效於s = s,但是這時你會發類的變量s與傳入的參數s同名,這裏會造成二定義,所以要加個this.表示等號左邊的s是當前類自己的變量 
this.s = s; 
Console.WriteLine("String & int args"); 

// 重載構造函數,: this("hi", 47) 表示調Car(String s, int petals) 這個重載的構造函數,並直接傳入變量"hi"和47 
Car() 
: this("hi", 47) 

Console.WriteLine("default constructor"); 

public static void Main() 

Car x = new Car(); 
Console.Read(); 


}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章