IRONSOFTWAREHOME
開發者更新

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

Jacob Mellor,首席技術官 @ Team Iron
Jacob Mellor
Updated: 2026年4月23日

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;
    }
}

在這種情況下,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;
    }
}

在無參數的構造函式中,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);
    }
}

在這裡,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; }
    }
}

在此類別 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.
    }
}

因此,請記住,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
    }
}

在上面的類別中,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);
    }
}

在學生類中,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);
    }
}

在這個 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!");
    }
}

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

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

結論

到目前為止,您應該對 C# 中的 this 關鍵字有了良好的理解,涵蓋其廣泛用途,從簡單的實例變數到復雜的背景,如構造函式、擴展方法、屬性、委託、匿名方法,甚至使用像 IronPDF 這樣的流行程式庫。

請記住,IronPDF 提供 免費的 IronPDF 試用,這樣您就可以測試今天所學的一切。 如果您決定繼續使用它,授權起價僅為 $999。 IronPDF 可以成為您 C# 開發工具包中的一個有價值的補充,簡化應用程式中 PDF 文件的處理任務。

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

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

...
閱讀更多

相關文章

Key in blue circle

立即免費取得 30 天試用金鑰

bullet_checked無需信用卡或建立帳號
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
預訂您的免費現場演示
Booking Badge

受到全球數百萬工程師的信任

Iron Software的客戶標誌
獲取您的無義務諮詢
填寫以下表格或電子郵件sales@ironsoftware.com
您的詳細資訊將始終保密
受到全球數百萬工程師的信任
Iron Software的客戶標誌
立即獲取您的30天試用金鑰
無需信用卡或帳戶建立