.NET 幫助

C# 索引器(為開發人員工作原理)

喬迪·巴迪亞
喬迪·巴迪亞
2024年10月23日
分享:

一個C# 中的索引器是一種特殊類型的屬性,使類或結構的實例可以使用陣列訪問運算子來訪問。[]. 索引器在創建「智慧陣列」或以簡化語法封裝資料方面非常有用。 它們提供了一種方法,可以像使用數組一樣使用類的實例,通過索引訪問數據。 本文將探討如何使用實際範例來宣告和使用 C# 索引器。 我們還將探討IronPDF 庫在文章結尾。

基本索引語法

索引器是在類別或結構中使用 'this' 關鍵字的實例成員,後接索引器宣告。 您還需要指定參數類型和返回類型。 索引器實例成員的一般語法如下:

public return_type this[parameter_type index]
{
    get
    {
        // code to return data
    }
    set
    {
        // set accessor, code to set data
    }
}
public return_type this[parameter_type index]
{
    get
    {
        // code to return data
    }
    set
    {
        // set accessor, code to set data
    }
}

在這裡,return_type 是索引器將返回的值類型,例如整數值,而 parameter_type 是索引的類型,通常是一個 int。 get 訪問子會返回指定索引處的值,而 set 區塊代碼訪問子則會給該索引賦值。

索引器宣告與使用

我們將探討在 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;
        }
    }
}
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;
        }
    }
}

在上述程式碼中:

  • Program 類別包含一個名為 values 的字串陣列。
  • 字串這個[int 索引]是索引器聲明,其中的 int index 是索引參數化屬性,用於訪問數組的元素。
  • get存取子返回指定索引處的索引值,而set存取子將索引值分配給該索引。
  • set 存取子設置給定索引的值。

    這意味著您可以創建 Program 類的實例並使用索引器訪問其 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
    }
}
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
    }
}

在此程式碼中,您可以看到索引器提供了一種簡單的語法來存取數值陣列,類似於您存取陣列中的元素的方式。

了解 get 和 set 存取子

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

get 區塊負責返回指定索引處的數據,而 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; }
    }
}
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; }
    }
}

在此範例中:

  • StudentRecords 類別有一個私有字符串[]studentNames 陣列用於存放學生的名字。
  • 索引器在設定或取得值之前,先檢查索引是否在陣列的範圍內。
  • int 類型的 Length 屬性提供對陣列長度的訪問。

    您可以在主方法中按以下方式使用此類別:

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

在這段程式碼中:

  • 泛型類別** 類別定義了一個可以與任何數據類型一起使用的索引器。
  • 「**this[int 索引]索引器允許您訪問陣列中的元素,無論其類型如何。

    您現在可以在 Main 方法中使用 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]);
        }
    }
}
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]);
        }
    }
}

將 IronPDF 與 C# Indexer 結合使用

C# 索引器(開發人員的工作方式):圖1 - IronPDF

IronPDF 是一個 C# 函式庫,用於在 .NET 應用程式中生成、編輯和轉換 PDF。 它簡化了開發人員處理 PDF 的工作,以便從HTML創建PDF,操作 PDF 文件,並以程式化方式處理合併、列印和添加簽名等進階功能。

您可以在使用索引器動態生成和管理 PDF 內容的 C# 程式中運用 IronPDF。 例如,假設您有一個包含 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.");
    }
}
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 所需的所有功能存取權。 您可以花時間探索這款軟體,滿意後可以購買授權,價格由 $749 起。

喬迪·巴迪亞
軟體工程師
Jordi 最擅長 Python、C# 和 C++,當他不在 Iron Software 發揮技能時,他會進行遊戲編程。他負責產品測試、產品開發和研究,為持續產品改進增添了巨大的價值。多樣化的經驗使他感到挑戰和投入,他說這是與 Iron Software 合作的最喜歡的方面之一。Jordi 在佛羅里達州邁阿密長大,並在佛羅里達大學學習計算機科學和統計學。
< 上一頁
C# 新的 GUID(如何為開發者運作)
下一個 >
C# foreach 與索引(開發者如何使用)