跳過到頁腳內容
.NET幫助

C# This(開發者的工作原理)

C# 中有一個特別重要的關鍵字,那就是 this 關鍵字。 這個關鍵字指的是使用它的當前類別實例。 除其他事項外,它可用於區分類別層級的變數和共用相同名稱的方法參數。 舉例來說,如果您有同名的實例變數和方法參數,this 可以成為您的救星!

此關鍵字的基礎知識

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

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

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

    public void Display(int id, string name)
    {
        // Use `this.id` to refer to the instance variable, 
        // and `id` for the method parameter.
        this.id = id;
        this.name = name;
    }
}
public class Employee
{
    private int id;
    private string name;

    public void Display(int id, string name)
    {
        // Use `this.id` to refer to the instance variable, 
        // and `id` for the method parameter.
        this.id = id;
        this.name = name;
    }
}
Public Class Employee
	Private id As Integer
	Private name As String

	Public Sub Display(ByVal id As Integer, ByVal name As String)
		' Use `this.id` to refer to the instance variable, 
		' and `id` for the method parameter.
		Me.id = id
		Me.name = name
	End Sub
End Class
$vbLabelText   $csharpLabel

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

this 結構器重載中的關鍵字。

透過利用 this 關鍵字,在相同的類別中,構建器重載成為一種強大的技術。 當一個類(例如 Student 類)有多個參數不一的構造器時,this 關鍵字允許一個構造器呼叫另一個構造器,省去了冗餘程式碼。

考慮以下範例,其中 this 用於參數化的建構子:

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

    public Student() : this("Default", 0)
    {
        // Default constructor delegates to the parameterized constructor
        // with "Default" as the name and 0 as the id.
    }

    public Student(string name, int id)
    {
        // Assign the parameters to the instance variables
        this.name = name;
        this.id = id;
    }
}
public class Student
{
    private string name;
    private int id;

    public Student() : this("Default", 0)
    {
        // Default constructor delegates to the parameterized constructor
        // with "Default" as the name and 0 as the id.
    }

    public Student(string name, int id)
    {
        // Assign the parameters to the instance variables
        this.name = name;
        this.id = id;
    }
}
Public Class Student
	Private name As String
	Private id As Integer

	Public Sub New()
		Me.New("Default", 0)
		' Default constructor delegates to the parameterized constructor
		' with "Default" as the name and 0 as the id.
	End Sub

	Public Sub New(ByVal name As String, ByVal id As Integer)
		' Assign the parameters to the instance variables
		Me.name = name
		Me.id = id
	End Sub
End Class
$vbLabelText   $csharpLabel

在無參數的構建器中,this("Default", 0) 會呼叫參數化的構建器,設定 Default 為名稱,0 為 ID。

探索擴充方法中的 this

C# 中的擴充方法提供了一種在不修改原始類型的情況下為現有類型增加方法的方法。 這裡是 this 關鍵字發揮神奇作用的地方。 它用在擴充方法的參數清單中,指代被擴充的類型。

請考慮以下擴充方法的範例:

public static class StringExtensions
{
    // This extension method can be called on any string instance
    public static bool IsNullOrEmpty(this string str)
    {
        return string.IsNullOrEmpty(str);
    }
}
public static class StringExtensions
{
    // This extension method can be called on any string instance
    public static bool IsNullOrEmpty(this string str)
    {
        return string.IsNullOrEmpty(str);
    }
}
Public Module StringExtensions
	' This extension method can be called on any string instance
	<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];

    // Define an indexer for the class
    public int this[int index]
    {
        get { return array[index]; }
        set { array[index] = value; }
    }
}
public class Test
{
    private int[] array = new int[100];

    // Define an indexer for the class
    public int this[int index]
    {
        get { return array[index]; }
        set { array[index] = value; }
    }
}
Public Class Test
	Private array(99) As Integer

	' Define an indexer for the class
	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; } // Use `this` to refer to the instance variable
    }
}
public class Employee
{
    private string name;

    public string Name
    {
        get { return this.name; }
        set { this.name = value; } // Use `this` to refer to the instance variable
    }
}
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 ' Use `this` to refer to the instance variable
	End Property
End Class
$vbLabelText   $csharpLabel

在上述類別中,在 Name 屬性的 get 和 set 存取器中,使用 this 關鍵字來參照私有字串 name

探索 this 和委託。

this 出現的另一個地方是代表。 C# 中的 delegate 類似於 C 或 C++ 中的函數指標。 它是一個引用型變數,持有方法的引用。 委託方法就像擴充方法一樣,可以使用 this 來存取目前的實體。

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

public delegate void DisplayDelegate();

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

    public void Display()
    {
        // `this.DisplayDetails` refers to the method instance of the current object.
        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()
    {
        // `this.DisplayDetails` refers to the method instance of the current object.
        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()
		' `this.DisplayDetails` refers to the method instance of the current object.
		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 關鍵字。

讓我們深入瞭解一個範例,您可能會將 this 關鍵字與 IronPDF結合使用,IronPDF 是一個功能強大的 .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)
    {
        // Creating a renderer to convert HTML content to PDF
        var Renderer = new IronPdf.ChromePdfRenderer();
        var PDF = Renderer.RenderHtmlAsPdf(content);

        // Save the generated PDF to the path specified by the current instance
        PDF.SaveAs(this.path);
    }
}
using IronPdf;

public class PDFHandler
{
    private string path;

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

    public void GeneratePDF(string content)
    {
        // Creating a renderer to convert HTML content to PDF
        var Renderer = new IronPdf.ChromePdfRenderer();
        var PDF = Renderer.RenderHtmlAsPdf(content);

        // Save the generated PDF to the path specified by the current instance
        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)
		' Creating a renderer to convert HTML content to PDF
		Dim Renderer = New IronPdf.ChromePdfRenderer()
		Dim PDF = Renderer.RenderHtmlAsPdf(content)

		' Save the generated PDF to the path specified by the current instance
		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)
    {
        // Initialize PDFHandler with a specified file path
        PDFHandler pdfHandler = new PDFHandler("C:\\ThisKeyword.pdf");
        pdfHandler.GeneratePDF("Hello World!");
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Initialize PDFHandler with a specified file path
        PDFHandler pdfHandler = new PDFHandler("C:\\ThisKeyword.pdf");
        pdfHandler.GeneratePDF("Hello World!");
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Initialize PDFHandler with a specified file path
		Dim pdfHandler As New PDFHandler("C:\ThisKeyword.pdf")
		pdfHandler.GeneratePDF("Hello World!")
	End Sub
End Class
$vbLabelText   $csharpLabel

在此,this 可使代碼更易閱讀和理解,尤其是在處理 IronPDF 等庫時。

C# This (How It Works For Developers) 圖 1

結論

到目前為止,您應該已經對 C# 中的 this 關鍵字有了相當的了解,包括其廣泛的用途,從簡單的實體變數到複雜的情境,例如:構造器、擴充方法、屬性、委託、匿名方法,甚至是在使用 IronPdf 等熱門函式庫時。

請記住,IronPDF 提供 免費的 IronPDF 試用版,讓您可以測試今天所學到的一切。 如果您決定繼續使用,授權僅需 \$liteLicense 起。 IronPDF 可以成為您 C# 開發工具包中值得一用的工具,簡化在應用程式中處理 PDF 檔案的工作。

常見問題解答

在 C# 中,'this' 關鍵字如何區分類變數和方法參數?

C# 中的「this」關鍵字是用來指當前的類實例,讓開發人員可以區分類等級變數和共用相同名稱的方法參數。這對避免方法內的命名衝突特別有用。

在構建器重載中,「this」有什麼意義?

在構建器重載中,'this' 可以讓一個構建器呼叫同一個類中的另一個構建器。這有助於透過重複使用現有的構建器邏輯來減少冗餘程式碼,確保一致性和可維護性。

this'如何方便使用 C# 中的擴充方法?

在擴充方法的方法參數清單中使用「this」關鍵字來表示被擴充的類型。這可讓開發人員在不修改現有類型的原始程式碼的情況下,為其新增新的方法,從而無縫地擴充其功能。

this "以何種方式用於索引器?

在 C# 中,'this' 與索引器一起使用來定義屬性,允許使用類似陣列的符號來存取類別的實體。這可增強物件內資料存取的可讀性和可用性。

為什麼 C# 中的靜態成員不能使用 'this'?

this "關鍵字指的是類別的實例成員,而靜態成員屬於類別本身,不屬於任何特定的實例。因此,'this' 不能用來參照靜態成員或方法。

this' 關鍵字如何增強 C# 類別中的屬性存取?

this」關鍵字可在屬性的 get 和 set 存取器中使用,以指當前類別實體的私有欄位。這可明確指出操作是在類別本身的欄位上執行,進而改善程式碼的清晰度。

這個」在代表的上下文中扮演什麼角色?

在委託的上下文中,「this」允許委託參照目前物件的方法實體。這對於透過委派函式來調用實例方法是非常重要的,可提供事件處理和回呼的彈性。

當使用 IronPDF 函式庫時,'this' 如何改善程式碼的可讀性?

在使用 IronPDF 函式庫時,'this' 可以清楚地指示檔案路徑等實例變數,讓程式碼更具可讀性。這在執行產生和儲存 PDF 檔案等作業時尤其有用,因為它可增強程式碼的清晰度和可維護性。

Jacob Mellor, Team Iron 首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技術官,作為 C# PDF 技術的先鋒工程師。作為 Iron Software 核心代碼的原作者,他自開始以來塑造了公司產品架構,與 CEO Cameron Rimington 一起將其轉變為一家擁有超過 50 名員工的公司,為 NASA、特斯拉 和 全世界政府機構服務。

Jacob 持有曼徹斯特大學土木工程一級榮譽学士工程學位(BEng) (1998-2001)。他於 1999 年在倫敦開設了他的第一家軟件公司,並於 2005 年製作了他的首個 .NET 組件,專注於解決 Microsoft 生態系統內的複雜問題。

他的旗艦產品 IronPDF & Iron Suite .NET 庫在全球 NuGet 被安裝超過 3000 萬次,其基礎代碼繼續為世界各地的開發工具提供動力。擁有 25 年的商業經驗和 41 年的編碼專業知識,Jacob 仍專注於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領袖。