在C#中,this關(guān)鍵字代表當(dāng)前實(shí)例,我們可以用this.來(lái)調(diào)用當(dāng)前實(shí)例的成員方法,變量,屬性,字段等;
也可以用this來(lái)做為參數(shù)狀當(dāng)前實(shí)例做為參數(shù)傳入方法.
還可以通過this[]來(lái)聲明索引器
下面是你這段程序的注解:
// 引入使命空間System
using System;
// 聲明命名空間CallConstructor
namespace CallConstructor
{
// 聲明類Car
public class Car
{
// 在Car類中:
// 聲明一個(gè)非靜態(tài)的整型變量petalCount,初始值為0
// 未用Static聲明的變量叫做靜態(tài)變量,非靜態(tài)成員屬于
//類的實(shí)例,我們只能在調(diào)用類的構(gòu)造函數(shù)對(duì)類進(jìn)行實(shí)例化后才能通過所得的實(shí)例加"."來(lái)訪問
int petalCount = 0;
// 聲明一個(gè)非靜態(tài)的字符串變量s,初始值為"null";
// 注意:s = "null"與s = null是不同的
String s = "null";
// Car類的默認(rèn)構(gòu)造函數(shù)
Car(int petals)
{
// Car類的默認(rèn)構(gòu)造函數(shù)中為 petalCount 賦值為傳入的參數(shù)petals的值
petalCount = petals;
// 輸出petalCount
Console.WriteLine("Constructor w/int arg only,petalCount = " + petalCount);
}
// 重載Car類的構(gòu)造函數(shù)
// : this(petals) 表示從當(dāng)前類中調(diào)用petals變量的值來(lái)作為構(gòu)造函數(shù)重載方法Car(String s, int
// petals)的第二個(gè)參數(shù)
Car(String s, int petals) : this(petals)
{
// 在構(gòu)造函數(shù)中為s賦值
// 非靜態(tài)成員可以在構(gòu)造函數(shù)或非靜態(tài)方法中使用this.來(lái)調(diào)用或訪問,也可以直接打變量的名字,因此這
//一句等效于s = s,但是這時(shí)你會(huì)發(fā)類的變量s與傳入的參數(shù)s同名,這里會(huì)造成二定義,所以要加個(gè)this.表
//示等號(hào)左邊的s是當(dāng)前類自己的變量
this.s = s;
Console.WriteLine("String & int args");
}
// 重載構(gòu)造函數(shù),: this("hi", 47) 表示調(diào)Car(String s, int petals) 這個(gè)重載的構(gòu)造函數(shù),并直接傳入
//變量"hi"和47
Car() : this("hi", 47)
{
Console.WriteLine("default constructor");
}
public static void Main()
{
Car x = new Car();
Console.Read();
}
}
}