.NET 幫助

C# 這個(它如何為開發者工作)

在C#中,有一個具有特殊重要性的關鍵字,那就是this關鍵字。 此關鍵字指的是用於當前 class 實例的參考。 它可以用來區分同名的類別層級變量與方法參數,以及其他用途。 例如,如果您有一個實例變數和一個具有相同名稱的方法參數,this 可以成為救星!

該關鍵字的基本知識

在公共類別中,例如Employee,你可能會有公共實例變數,例如idname。 如果您想在方法內為這些實例變數賦值,可能會遇到一個常見問題:如果方法參數與實例變數同名該怎麼辦?

這裡有一個解決方案:使用this 關鍵字在 C# 文件中! 在以下的公共類別Employee的方法範例中,this關鍵字用於區分實例變數和具有相同名稱的方法參數。

public void Display(int id, string name)
{
    this.id = id;
    this.name = name;
}
public void Display(int id, string name)
{
    this.id = id;
    this.name = name;
}
Public Sub Display(ByVal id As Integer, ByVal name As String)
	Me.id = id
	Me.name = name
End Sub
$vbLabelText   $csharpLabel

在這種情況下,this.id 指的是實例變量,而 id 是方法參數。

在建構函式多載中的this關鍵字

透過利用this關鍵字,建構子多載在同一個類別中成為了一個強大的技術。 當一個類,例如 student 類,擁有多個帶有不同參數的構造函數時,this 關鍵字允許一個構造函數調用另一個,從而消除冗餘的代碼。

考慮以下使用this於參數化構造函數中的範例:

public class Student
{
    private string name;
    private int id;

    public Student() : this("Default", 0)
    {
    }

    public Student(string name, int id)
    {
        this.name = name;
        this.id = id;
    }
}
public class Student
{
    private string name;
    private int id;

    public Student() : this("Default", 0)
    {
    }

    public Student(string name, int id)
    {
        this.name = name;
        this.id = id;
    }
}
Public Class Student
	Private name As String
	Private id As Integer

	Public Sub New()
		Me.New("Default", 0)
	End Sub

	Public Sub New(ByVal name As String, ByVal id As Integer)
		Me.name = name
		Me.id = id
	End Sub
End Class
$vbLabelText   $csharpLabel

在無參數的建構子中,this("Default", 0) 呼叫了帶參數的建構子,將 Default 設定為名稱和 ID。

在擴展方法中探索this

C#中的擴充方法為現有類型添加方法提供了一種方式,無需修改原始類型。 這就是this關鍵字發揮神奇作用的地方。 它用於擴展方法的參數列表中,以指代被擴展的類型。

請考慮以下擴展方法的例子:

public static class StringExtensions
{
    public static bool IsNullOrEmpty(this string str)
    {
        return string.IsNullOrEmpty(str);
    }
}
public static class StringExtensions
{
    public static bool IsNullOrEmpty(this string str)
    {
        return string.IsNullOrEmpty(str);
    }
}
Public Module StringExtensions
	<System.Runtime.CompilerServices.Extension> _
	Public Function IsNullOrEmpty(ByVal str As String) As Boolean
		Return String.IsNullOrEmpty(str)
	End Function
End Module
$vbLabelText   $csharpLabel

這裡,this string str 告訴 C# 這是一個用於字串類型的擴充方法。 現在您可以在任何字串物件上使用此方法,例如 if(myString.IsNullOrEmpty())

索引器中的this

this 關鍵字也可以用於定義索引器。 索引器允許類別的實例像數組一樣被索引。 這可以幫助您使用類似索引的符號來訪問物件中的數據。 在索引器中,this 後跟一個陣列索引,通常是 int index

以下是一個索引器的基本範例:

public class Test
{
    private int [] array = new int [100];

    public int this [int index]
    {
        get { return array [index]; }
        set { array [index] = value; }
    }
}
public class Test
{
    private int [] array = new int [100];

    public int this [int index]
    {
        get { return array [index]; }
        set { array [index] = value; }
    }
}
Public Class Test
	Private array(99) As Integer

	Default Public Property Item(ByVal index As Integer) As Integer
		Get
			Return array (index)
		End Get
		Set(ByVal value As Integer)
			array (index) = value
		End Set
	End Property
End Class
$vbLabelText   $csharpLabel

在這個類別 Test 中,關鍵字 this 定義了一個索引子,可用於取得或設置 array 實例欄位中的值。

this與靜態成員

需要注意的一點是,this 無法用來引用靜態成員或方法。 這是因為this指的是當前實例,而靜態成員屬於類本身,而不是類的實例。

public class Program
{
    public static void Main(string [] args)
    {
        // Can't use `this` here, because 'Main' is a static method.
    }
}
public class Program
{
    public static void Main(string [] args)
    {
        // Can't use `this` here, because 'Main' is a static method.
    }
}
Public Class Program
	Public Shared Sub Main(ByVal args() As String)
		' Can't use `this` here, because 'Main' is a static method.
	End Sub
End Class
$vbLabelText   $csharpLabel

所以,記住,this 是用於實例的,不能用於類別層級或靜態成員!

this 關鍵字和屬性

就像實例變量和方法參數一樣,this 關鍵字也可以用於屬性。 在C#中,屬性是一個成員,提供了一種靈活的機制來讀取、寫入或計算私有欄位的值。 屬性可以像公共數據成員一樣使用,但它們實際上是稱為存取子的方法。

讓我們來看看在屬性中使用this的一個簡單例子:

public class Employee
{
    private string name;

    public string Name
    {
        get { return this.name; }
        set { this.name = value; }
    }
}
public class Employee
{
    private string name;

    public string Name
    {
        get { return this.name; }
        set { this.name = value; }
    }
}
Public Class Employee
'INSTANT VB NOTE: The field name was renamed since Visual Basic does not allow fields to have the same name as other class members:
	Private name_Conflict As String

	Public Property Name() As String
		Get
			Return Me.name_Conflict
		End Get
		Set(ByVal value As String)
			Me.name_Conflict = value
		End Set
	End Property
End Class
$vbLabelText   $csharpLabel

在上面的類別中,this 關鍵字用於在 Name 屬性的 get 和 set 存取器中引用私人字串 name

探索this與委派

另一個出現this的地方是在委派中。 C# 中的委派類似於 C 或 C++ 中的函數指標。 這是一種引用類型的變數,用於保存對方法的引用。 委派方法與擴展方法一樣,可以使用this來訪問當前實例。

這是一個使用this的委託範例:

public delegate void DisplayDelegate();

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }

    public void Display()
    {
        DisplayDelegate displayDelegate = new DisplayDelegate(this.DisplayDetails);
        displayDelegate();
    }

    private void DisplayDetails()
    {
        Console.WriteLine("ID: " + Id + ", Name: " + Name);
    }
}
public delegate void DisplayDelegate();

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }

    public void Display()
    {
        DisplayDelegate displayDelegate = new DisplayDelegate(this.DisplayDetails);
        displayDelegate();
    }

    private void DisplayDetails()
    {
        Console.WriteLine("ID: " + Id + ", Name: " + Name);
    }
}
Public Delegate Sub DisplayDelegate()

Public Class Student
	Public Property Id() As Integer
	Public Property Name() As String

	Public Sub Display()
		Dim displayDelegate As New DisplayDelegate(AddressOf Me.DisplayDetails)
		displayDelegate()
	End Sub

	Private Sub DisplayDetails()
		Console.WriteLine("ID: " & Id & ", Name: " & Name)
	End Sub
End Class
$vbLabelText   $csharpLabel

在學生類別中,this.DisplayDetails 創建了一個新的委派實例,該實例引用了當前物件的 DisplayDetails 方法。

使用 IronPDF 實作this 關鍵字

讓我們深入了解一個例子,其中您可能會在使用IronPDF時將this關鍵字與這個強大的.NET函式庫結合,以編輯和使用HTML創建PDF文件

考慮一個名為PDFHandler的類別,該類別使用IronPDF庫來對PDF文件執行各種操作:

using IronPdf;

public class PDFHandler
{
    private string path;

    public PDFHandler(string path)
    {
        this.path = path;
    }

    public void GeneratePDF(string content)
    {
        var Renderer = new IronPdf.ChromePdfRenderer();
        var PDF = Renderer.RenderHtmlAsPdf(content);
        PDF.SaveAs(this.path);
    }
}
using IronPdf;

public class PDFHandler
{
    private string path;

    public PDFHandler(string path)
    {
        this.path = path;
    }

    public void GeneratePDF(string content)
    {
        var Renderer = new IronPdf.ChromePdfRenderer();
        var PDF = Renderer.RenderHtmlAsPdf(content);
        PDF.SaveAs(this.path);
    }
}
Imports IronPdf

Public Class PDFHandler
	Private path As String

	Public Sub New(ByVal path As String)
		Me.path = path
	End Sub

	Public Sub GeneratePDF(ByVal content As String)
		Dim Renderer = New IronPdf.ChromePdfRenderer()
		Dim PDF = Renderer.RenderHtmlAsPdf(content)
		PDF.SaveAs(Me.path)
	End Sub
End Class
$vbLabelText   $csharpLabel

在這個PDFHandler類別中,this關鍵字用於引用當前實例的path欄位。 此欄位用於將生成的 PDF 儲存到指定的路徑。

當我們創建一個新的PDFHandler實例並調用GeneratePDF方法時,this關鍵字允許我們使用在創建對象時指定的path

class Program
{
    static void Main(string [] args)
    {
        PDFHandler pdfHandler = new PDFHandler("C:\\ThisKeyowrd.pdf");
        pdfHandler.GeneratePDF("Hello World!");
    }
}
class Program
{
    static void Main(string [] args)
    {
        PDFHandler pdfHandler = new PDFHandler("C:\\ThisKeyowrd.pdf");
        pdfHandler.GeneratePDF("Hello World!");
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim pdfHandler As New PDFHandler("C:\ThisKeyowrd.pdf")
		pdfHandler.GeneratePDF("Hello World!")
	End Sub
End Class
$vbLabelText   $csharpLabel

在這裡,this讓程式碼變得更易讀且易於理解,特別是在處理像 IronPDF 這樣的資料庫時。

C# This(針對開發人員的運作方式)圖1

結論

到現在為止,您應該已經對 C# 中的 this 關鍵字有了很好的理解,包括它的廣泛用途,從簡單的實例變量到如構造函數、擴展方法、屬性、委託、匿名方法等複雜上下文,甚至在使用像 IronPDF 這樣的流行庫時。

請記住,IronPDF 提供免費試用版,因此您可以測試您今天所學的一切。 如果您決定繼續使用,許可證起始價格僅為 \$liteLicense。 IronPDF 可以成為您的 C# 開發工具包中值得一提的補充,簡化在應用程式中處理 PDF 文件的任務。

Chipego
奇佩戈·卡林达
軟體工程師
Chipego 擁有天生的傾聽技能,這幫助他理解客戶問題,並提供智能解決方案。他在獲得信息技術理學學士學位後,于 2023 年加入 Iron Software 團隊。IronPDF 和 IronOCR 是 Chipego 專注的兩個產品,但隨著他每天找到新的方法來支持客戶,他對所有產品的了解也在不斷增長。他喜歡在 Iron Software 的協作生活,公司內的團隊成員從各自不同的經歷中共同努力,創造出有效的創新解決方案。當 Chipego 離開辦公桌時,他常常享受讀好書或踢足球的樂趣。
< 上一頁
C# 新手指南 (開發者使用方式)
下一個 >
C# 列表(開發者使用指南)