在C#程式語言中,
this
關鍵字是一個特殊的參照,它指向當前類的例項。
this
關鍵字在類的方法內部使用,主要用於參照當前例項的成員。以下是
this
關鍵字的三種常見用法,並透過範例程式碼進行解釋。
1. 參照當前例項的成員
當類的方法或內容中的參數或局部變量與類的成員名稱沖突時,可以使用
this
關鍵字來明確指定我們正在參照的是當前例項的成員,而不是局部變量或參數。
範例程式碼:
public classPerson
{
privatestring name;
publicPerson(string name)
{
// 使用 this 關鍵字來區分成員變量和建構函式的參數
this.name = name;
}
publicvoidSetName(string name)
{
// 同樣使用 this 關鍵字來參照成員變量
this.name = name;
}
publicstringGetName()
{
returnthis.name;
}
}
在這個例子中,
this.name
指的是類的私有成員變量
name
,而不是方法或建構函式的參數
name
。
2. 作為方法的返回值
this
關鍵字還可以用作方法的返回值,通常用於實作鏈式呼叫(也稱為流暢介面)。當方法返回
this
時,它實際上返回的是當前物件的參照,允許我們在同一物件上連續呼叫多個方法。
範例程式碼:
public classBuilder
{
privatestring material;
privateint size;
public Builder SetMaterial(string material)
{
this.material = material;
// 返回當前例項的參照,以便進行鏈式呼叫
returnthis;
}
public Builder SetSize(int size)
{
this.size = size;
// 返回當前例項的參照,以便進行鏈式呼叫
returnthis;
}
publicvoidBuild()
{
Console.WriteLine($"Building with {material} of size {size}");
}
}
// 使用範例:
Builder builder = new Builder();
builder.SetMaterial("Wood").SetSize(10).Build(); // 鏈式呼叫
在這個例子中,
SetMaterial
和
SetSize
方法都返回
this
,這使得我們可以將方法呼叫連結在一起。
3. 在索引器中使用
this
關鍵字還可以用於定義索引器,索引器允許一個類或結構的物件像陣列一樣進行索引。在這種情況下,
this
關鍵字用於指定索引器的存取方式。
範例程式碼:
public classCustomArray
{
privateint[] array = newint[10];
// 索引器定義,使用 this 關鍵字
publicintthis[int index]
{
get { return array[index]; }
set { array[index] = value; }
}
}
// 使用範例:
CustomArray customArray = new CustomArray();
customArray[0] = 100; // 設定第一個元素的值
Console.WriteLine(customArray[0]); // 獲取並打印第一個元素的值
在這個例子中,我們定義了一個名為
CustomArray
的類,它使用
this
關鍵字建立了一個索引器,允許我們像存取陣列元素一樣存取
CustomArray
物件的成員。
總結
this
關鍵字在C#中扮演著重要角色,它提供了對當前例項的參照,使得在方法內部能夠清晰地存取和修改例項的成員。透過了解
this
關鍵字的這三種常見用法,開發者可以更加靈活地編寫物件導向的程式碼,並實作更優雅的編程風格。