在生產環境中測試,無水印。
在任何需要的地方都能運行。
獲得 30 天的全功能產品。
在幾分鐘內上手運行。
試用產品期間完全訪問我們的支援工程團隊
在C#中,有一個具有特殊重要性的關鍵字,那就是this
關鍵字。 此關鍵字指的是用於當前 class 實例的參考。 它可以用來區分同名的類別層級變量與方法參數,以及其他用途。 例如,如果您有一個實例變數和一個具有相同名稱的方法參數,this
可以成為救星!
在公共類別中,例如Employee
,你可能會有公共實例變數,例如id
或name
。 如果您想在方法內為這些實例變數賦值,可能會遇到一個常見問題:如果方法參數與實例變數同名該怎麼辦?
這裡有一個解決方案:使用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
在這種情況下,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
在無參數的建構子中,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
這裡,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
在這個類別 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
所以,記住,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
在上面的類別中,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
在學生類別中,this.DisplayDetails
創建了一個新的委派實例,該實例引用了當前物件的 DisplayDetails
方法。
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
在這個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
在這裡,this
讓程式碼變得更易讀且易於理解,特別是在處理像 IronPDF 這樣的資料庫時。
到現在為止,您應該已經對 C# 中的 this
關鍵字有了很好的理解,包括它的廣泛用途,從簡單的實例變量到如構造函數、擴展方法、屬性、委託、匿名方法等複雜上下文,甚至在使用像 IronPDF 這樣的流行庫時。
請記住,IronPDF 提供免費試用版,因此您可以測試您今天所學的一切。 如果您決定繼續使用,許可證起始價格僅為 \$liteLicense。 IronPDF 可以成為您的 C# 開發工具包中值得一提的補充,簡化在應用程式中處理 PDF 文件的任務。