在C#中,this關鍵字代表當前實例,我們可以用this.來調用當前實例的成員方法,變量,屬性,字段等;也可以用this來做為參數狀當前實例做為參數傳入方法.還可以通過this[]來聲明索引器下面是你這段程序的注解:// 引入使命空間Systemusing System;// 聲明命名空間CallConstructornamespace CallConstructor{// 聲明類Carpublic 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;// 輸出petalCountConsole.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"和47Car(): this("hi", 47){Console.WriteLine("default constructor");}public static void Main(){Car x = new Car();Console.Read();}}}
新聞熱點
疑難解答