IRONSOFTWAREHOME
開發者更新

C#索引器(對開發者如何理解的工作)

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

C#中的索引器是一種特殊型別的屬性,使得類或結構的實例可以使用陣列存取操作符[]進行存取。 索引器在建立"智能陣列"或簡化語法封裝資料方面非常有用。 它們提供了一種使用類實例的方法,就像使用陣列一樣,您可以通過索引存取資料。 本文將探討如何使用實際範例宣告並使用C#索引器。 我們還將在文章末尾探討IronPDF程式庫

基本索引器語法

索引器是一個使用this關鍵字的實例成員,位於類或結構中,後面是索引器宣告。 您還必須指定參數型別和返回型別。 索引器實例成員的一般語法如下:

public return_type this[parameter_type index]
{
    get
    {
        // Code to return data
    }
    set
    {
        // Code to set data
    }
}

在這裡,intset塊程式碼存取器將值分配給該索引。

索引器宣告和使用

我們將檢查在C#類中實作索引器的基本範例。 考慮一個封裝字串陣列的類Program

class Program
{
    private string[] values = new string[5]; // Array with 5 elements
    public string this[int index]
    {
        get
        {
            return values[index];
        }
        set
        {
            values[index] = value;
        }
    }
}

在上述程式碼中:

  • values的字串陣列。
  • int index是用於存取陣列元素的參數屬性。
  • set存取器將索引值分配給該索引。

這意味著您可以建立values陣列,如下所示:

class Program
{
    static void Main()
    {
        Program program = new Program();
        // Set values using indexer
        program[0] = "First";
        program[1] = "Second";
        // Access values using indexer
        Console.WriteLine(program[0]); // Output: First
        Console.WriteLine(program[1]); // Output: Second
    }
}

在此程式碼中,您可以看到索引器為存取values陣列提供了簡化的語法,類似於存取陣列中的元素。

了解set存取器

索引器內的set存取器就像塊程式碼,允許您以類似於屬性的方式檢索和分配資料。 主要區別在於,索引器使用一個索引參數來處理資料集合,而不是單個資料成員。

set塊將資料分配給指定索引。 這是另一個例子以加深您的理解:

class StudentRecords
{
    private string[] studentNames = new string[3];
    public string this[int index]
    {
        get
        {
            if (index >= 0 && index < studentNames.Length)
            {
                return studentNames[index];
            }
            return "Invalid Index";
        }
        set
        {
            if (index >= 0 && index < studentNames.Length)
            {
                studentNames[index] = value;
            }
        }
    }
    public int Length
    {
        get { return studentNames.Length; }
    }
}

在此範例中:

  • string[] studentNames陣列儲存著學生的名字。
  • 索引器在設置或檢索值之前會檢查索引是否在陣列範圍內。
  • 一個Length屬性提供了對陣列長度的存取。

您可以在Main方法中使用此類,如下所示:

class Program
{
    public static void Main()
    {
        StudentRecords records = new StudentRecords();
        // Set values using indexer
        records[0] = "John";
        records[1] = "Jane";
        records[2] = "Bob";
        // Access values using indexer
        for (int i = 0; i < records.Length; i++)
        {
            Console.WriteLine(records[i]);
        }
    }
}

建立通用索引器

您也可以建立具有索引器的通用類,讓您的程式碼處理多種資料型別。這是帶有通用索引器的通用類的簡單範例:

class GenericClass<t>
{
    private T[] elements = new T[5];
    public T this[int index]
    {
        get
        {
            return elements[index];
        }
        set
        {
            elements[index] = value;
        }
    }
    public int Length
    {
        get { return elements.Length; }
    }
}

在這段程式碼中:

  • GenericClass類定義了一個可以與任何資料型別一起使用的索引器。
  • this[int index]索引器允許您存取陣列中的元素,無論型別如何。

您可以在GenericClass

class Program
{
    public static void Main()
    {
        GenericClass<int> intArray = new GenericClass<int>();
        intArray[0] = 10;
        intArray[1] = 20;

        GenericClass<string> stringArray = new GenericClass<string>();
        stringArray[0] = "Hello";
        stringArray[1] = "World";

        // Output the integer array values
        for (int i = 0; i < intArray.Length; i++)
        {
            Console.WriteLine(intArray[i]);
        }

        // Output the string array values
        for (int i = 0; i < stringArray.Length; i++)
        {
            Console.WriteLine(stringArray[i]);
        }
    }
}

在C#索引器中使用IronPDF

C#索引器(這對開發者的作用):圖1 - IronPDF

IronPDF是一個C#的程式庫,專為在.NET應用中生成、編輯和轉換PDF而設計。 它簡化了開發者處理PDF的過程,讓您可以從HTML建立PDF,操作PDF文件,並以程式化方式處理如合併、列印和新增簽名等高級功能。

您可以在使用索引器的C#程式中利用IronPDF,以動態生成和管理PDF內容。 例如,假設您有一個包含HTML字串的類,並希望使用索引器為每個HTML條目生成PDF。 此方法簡化PDF生成,同時保持您的程式碼組織有序且直觀。

using IronPdf;
using System;

class PdfGenerator
{
    private string[] htmlTemplates = new string[3];
    public string this[int index]
    {
        get { return htmlTemplates[index]; }
        set { htmlTemplates[index] = value; }
    }

    public void GeneratePdf(int index, string outputPath)
    {
        var renderer = new ChromePdfRenderer();
        var pdfDocument = renderer.RenderHtmlAsPdf(this[index]); // Access HTML string using indexer
        pdfDocument.SaveAs(outputPath);
    }
}

class Program
{
    public static void Main()
    {
        PdfGenerator pdfGen = new PdfGenerator();
        // Populate HTML templates
        pdfGen[0] = "<h1>First Document</h1><p>This is the first PDF.</p>";
        pdfGen[1] = "<h1>Second Document</h1><p>This is the second PDF.</p>";
        pdfGen[2] = "<h1>Third Document</h1><p>This is the third PDF.</p>";

        // Generate PDFs using the indexer
        pdfGen.GeneratePdf(0, "first.pdf");
        pdfGen.GeneratePdf(1, "second.pdf");
        pdfGen.GeneratePdf(2, "third.pdf");

        Console.WriteLine("PDFs generated successfully.");
    }
}

C#索引器(這對開發者的作用):圖2 - 控制台輸出

結論

C#索引器是一個有用的功能,有助於使您的類和結構行為類似於陣列。 通過提供簡化的語法和靈活的資料存取,您可以建立更直觀和易讀的程式碼。 無論您是在處理字串、整數或任何其他資料型別,索引器都讓您能夠封裝資料結構,並使用索引以幹淨和高效的方式存取它。

IronPDF使您可以輕鬆開始免費試用,這讓您可以存取建立、操作和渲染PDF所需的所有功能。 您可以慢慢探索該軟體,當您滿意後,可以從$999開始購買授權。

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天試用金鑰
無需信用卡或帳戶建立