跳至頁尾內容
開發者更新

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

在上面的類別中,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()
    {
        // `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,這是用於編輯和 使用 HTML 建立 PDF 文件的強大 .NET 程式庫。

考慮一個名為 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) Figure 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#類別內的屬性存取?

在屬性的get和set存取子中可以使用'this'關鍵字來引用當前類別實例的私有字段。這通過明確指出操作是在類別自己的字段上執行的來提高程式碼的清晰度。

'this'在委派的上下文中扮演什麼角色?

在委派的上下文中,'this'允許委派引用當前物件的方法實例。這對於通過委派調用實例方法至為關鍵,提供了事件處理和回調的靈活性。

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

在使用IronPDF程式庫時,'this'可以使程式碼更具可讀性,通過明確指示實例變數(如文件路徑)。這在執行生成和保存PDF文件等操作時特別有用,因為它增強了程式碼的清晰度和可維護性。

Jacob Mellor,首席技術官 @ Team Iron
首席技術官

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

Jacob擁有曼徹斯特大學的土木工程一等榮譽學士學位(BEng),於1998-2001年之間獲得。在1999年於倫敦創辦他的第一家軟體公司並於2005年建立了他的第一批.NET元組件後,他專注於解決Microsoft生態系統中的複雜問題。

他的旗艦IronPDF和Iron Suite .NET程式庫在全球獲得了超過3000萬次NuGet安裝依據,他的基礎程式碼基繼續支援著世界各地開發者使用的工具。擁有25年的商業經驗和41年的程式設計專業知識,他仍專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話