1. 程式人生 > >c#中this的用法及作用

c#中this的用法及作用

sys 靜態成員 mes 成員 成員方法 read 訪問 write stat

在C#中,

1. this關鍵字代表當前實例,我們可以用this.來調用當前實例的成員方法,變量,屬性,字段等;

2. 也可以用this來做為參數狀當前實例做為參數傳入方法.

3. 還可以通過this[]來聲明索引器

下面用一段程序來展示一下this的使用:

// 引入使命空間System using System;
// 聲明命名空間CallConstructor namespace CallConstructor {
// 聲明類Car

public class Car

{
// 未用Static聲明的變量叫做非靜態成員
//類的實例,我們只能在調用類的構造函數對類進行實例化後才能通過所得的實例加"."來訪問

int petalCount = 0; // 在Car類中聲明一個非靜態的整型變量petalCount,初始值為0
String s = "null"; // 聲明一個非靜態的字符串變量s,初始值為"null";註意:s = "null"與s = null是不同的
// Car類的默認構造函數

Car(int petals)

{
petalCount = petals; // Car類的默認構造函數中為 petalCount 賦值為傳入的參數petals的值

Console.WriteLine("Constructor w/int arg only,petalCount = " + 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();

}

c#中this的用法及作用