.NET 幫助

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

發佈 2023年6月13日
分享:

在 C# 中,有一个特别重要的关键字,那就是 this 关键字。这个关键字引用当前类的实例。它可以用来区分同名的类级变量和方法参数,以及其他用途。例如,如果你有一个实例变量和一个同名的方法参数,this 可以派上用场。!

這個關鍵字的基礎知識

在一個公共類,如 Employee (員工) 為例,你可能有像 idname 這樣的公共實例變量。如果你想在方法內為這些實例變量賦值,你可能會遇到一個常見的問題:如果方法參數與實例變量同名怎麼辦?

這裡有一個解決方案:使用 this 關鍵字! 在以下公共类 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
VB   C#

在這種情況下,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
VB   C#

在沒有參數的建構函數中,this("預設", 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
VB   C#

這裡,this string str 告訴 C# 這是一個針對 string 類型的擴展方法。現在您可以在任何字符串對象上使用這個方法,例如 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
VB   C#

在這個類別 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
VB   C#

所以,請記住,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
VB   C#

在上述類別中,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
VB   C#

在學生類別中,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)
    {
        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
VB   C#

在這個 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
VB   C#

在這裡,this 使代碼更加易讀和易理解,特別是當處理像 IronPDF 這樣的庫時。

C# 這是(開發者如何工作)圖1

結論

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

記住,IronPDF 提供了 免費試用,因此您可以測試今天所學到的所有內容。如果您決定繼續使用,許可證起價僅為 $liteLicense。IronPDF 可以成為您 C# 開發工具包中的一個值得的添加,使在應用程序中處理 PDF 文件的任務變得簡單。

< 上一頁
C# 新手指南 (開發者使用方式)
下一個 >
C# 列表(開發者使用指南)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >