跳過到頁腳內容
.NET幫助

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

C#中的索引器是一種特殊類型的屬性,它使類或結構體中的實例可以使用陣列存取運算符 [] 來存取。 索引器對於建立"智慧型陣列"或以簡化的語法封裝資料非常有用。 這些工具提供使用類的實例的方法,就像使用陣列一樣,您可以透過索引存取資料。 本文將以實例探討如何宣告和使用 C# 索引器。 而我們也會在文章的最後探討 IronPDF 函式庫

基本索引器語法

索引器是在類別或結構體中使用 this 關鍵字的實例成員,其後是索引器宣告。 您也可以指定參數類型和回傳類型。 索引器實例成員的一般語法如下:

public return_type this[parameter_type index]
{
    get
    {
        // Code to return data
    }
    set
    {
        // Code to set data
    }
}
public return_type this[parameter_type index]
{
    get
    {
        // Code to return data
    }
    set
    {
        // Code to set data
    }
}
Default Public Property Item(ByVal index As parameter_type) As return_type
	Get
		' Code to return data
	End Get
	Set(ByVal value As return_type)
		' Code to set data
	End Set
End Property
$vbLabelText   $csharpLabel

這裡,return_type 是索引器將會返回的值類型,例如整數值,而 parameter_type 則是索引的類型,通常是 intget 存取器會回傳指定索引的值,而 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;
        }
    }
}
Friend Class Program
	Private values(4) As String ' Array with 5 elements
	Default Public Property Item(ByVal index As Integer) As String
		Get
			Return values(index)
		End Get
		Set(ByVal value As String)
			values(index) = value
		End Set
	End Property
End Class
$vbLabelText   $csharpLabel

在上述程式碼中

  • Program 類包含一個名為 values 的字串陣列。
  • string this[int index] 是索引器宣告,其中 int index 是索引參數化的屬性,用來存取陣列中的元素。
  • get 存取器會回傳指定索引的索引值,而 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
    }
}
Friend Class Program
	Shared Sub Main()
		Dim program As 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
	End Sub
End Class
$vbLabelText   $csharpLabel

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

瞭解 getset 存取器。

索引器內的 getset 存取器就像是區塊程式碼,可讓您擷取和指派資料,就像使用屬性一樣。 主要差異在於索引器使用索引參數來處理資料集合,而非個別資料成員。

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; }
    }
}
Friend Class StudentRecords
	Private studentNames(2) As String
	Default Public Property Item(ByVal index As Integer) As String
		Get
			If index >= 0 AndAlso index < studentNames.Length Then
				Return studentNames(index)
			End If
			Return "Invalid Index"
		End Get
		Set(ByVal value As String)
			If index >= 0 AndAlso index < studentNames.Length Then
				studentNames(index) = value
			End If
		End Set
	End Property
	Public ReadOnly Property Length() As Integer
		Get
			Return studentNames.Length
		End Get
	End Property
End Class
$vbLabelText   $csharpLabel

在這個範例中

  • StudentRecords 類有一個私有的 string[] studentNames 陣列,用來存放學生的姓名。
  • 在設定或擷取值之前,索引器會檢查索引是否在陣列的範圍內。
  • 一個 int 類型的 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 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]);
        }
    }
}
Friend Class Program
	Public Shared Sub Main()
		Dim records As New StudentRecords()
		' Set values using indexer
		records(0) = "John"
		records(1) = "Jane"
		records(2) = "Bob"
		' Access values using indexer
		For i As Integer = 0 To records.Length - 1
			Console.WriteLine(records(i))
		Next i
	End Sub
End Class
$vbLabelText   $csharpLabel

建立通用索引器

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

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; }
    }
}
Friend Class GenericClass(Of T)
	Private elements(4) As T
	Default Public Property Item(ByVal index As Integer) As T
		Get
			Return elements(index)
		End Get
		Set(ByVal value As T)
			elements(index) = value
		End Set
	End Property
	Public ReadOnly Property Length() As Integer
		Get
			Return elements.Length
		End Get
	End Property
End Class
$vbLabelText   $csharpLabel

在此程式碼中

  • GenericClass 類定義了一個可以處理任何資料類型的索引器。
  • this[int index] 索引器允許您存取陣列中的元素,不論其類型為何。

現在您可以在 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]);
        }
    }
}
Friend Class Program
	Public Shared Sub Main()
		Dim intArray As New GenericClass(Of Integer)()
		intArray(0) = 10
		intArray(1) = 20

		Dim stringArray As New GenericClass(Of String)()
		stringArray(0) = "Hello"
		stringArray(1) = "World"

		' Output the integer array values
		For i As Integer = 0 To intArray.Length - 1
			Console.WriteLine(intArray(i))
		Next i

		' Output the string array values
		For i As Integer = 0 To stringArray.Length - 1
			Console.WriteLine(stringArray(i))
		Next i
	End Sub
End Class
$vbLabelText   $csharpLabel

使用 IronPDF 與 C# 索引器。

C# Indexers (How It Works For Developers):圖 1 - IronPdf

IronPDF 是專為在 .NET 應用程式中產生、編輯和轉換 PDF 而設計的 C# 函式庫。 它簡化了開發人員使用 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.");
    }
}
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.");
    }
}
Imports IronPdf
Imports System

Friend Class PdfGenerator
	Private htmlTemplates(2) As String
	Default Public Property Item(ByVal index As Integer) As String
		Get
			Return htmlTemplates(index)
		End Get
		Set(ByVal value As String)
			htmlTemplates(index) = value
		End Set
	End Property

	Public Sub GeneratePdf(ByVal index As Integer, ByVal outputPath As String)
		Dim renderer = New ChromePdfRenderer()
		Dim pdfDocument = renderer.RenderHtmlAsPdf(Me(index)) ' Access HTML string using indexer
		pdfDocument.SaveAs(outputPath)
	End Sub
End Class

Friend Class Program
	Public Shared Sub Main()
		Dim pdfGen As 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.")
	End Sub
End Class
$vbLabelText   $csharpLabel

C# Indexers (How It Works For Developers):圖 2 - 控制台輸出

結論

C# 索引器是一項有用的功能,可協助您讓類別和結構體表現得像陣列一樣。 透過提供簡化的語法和彈性的資料存取,您可以建立更直覺、更易讀的程式碼。 無論您處理的是字串、整數或任何其他資料類型,索引器都能讓您封裝資料結構,並使用索引乾淨、有效率地存取資料。

IronPDF 提供 免費試用,讓您輕鬆上手,使用所有功能來建立、處理和渲染 PDF。 您可以慢慢探索軟體,一旦您感到滿意,即可取得授權,起價為 $799 。

常見問題解答

什麼是 C# 中的索引器?

C# 中的索引器是一種特殊類型的屬性,允許使用陣列存取操作符 [] 來存取類別或結構體中的實例。它提供了一種使用類的實例的方法,就像使用陣列一樣。

如何在 C# 中宣告基本索引器?

C# 中的基本索引器是使用'this'關鍵字來宣告的,接著是索引器宣告。您必須指定參數類型和回傳類型。例如public return_type this[parameter_type index] { get; set; }

索引器中的 'get「 和 」set' 存取器有何作用?

索引器中的「get」存取器用於擷取指定索引中的資料,而「set」存取器則用於指定索引中的資料。它們的功能類似於屬性存取器,但用於資料集合。

您能提供 C# 類別中索引器的範例嗎?

當然,考慮一個具有私有字串陣列的類別「Program」。索引器允許使用整數索引存取此陣列。例如public string this[int index] { get { return values[index]; } set { values[index] = value; }。}.

如何在 C# 中建立一般索引器?

C# 中的泛型索引器可以在泛型類別中建立。例如,類 GenericClass 包含一個可以處理任何資料類型的索引器。索引器宣告為 public T this[int index] { get; set; }

如何在 C# 中使用索引器來簡化 PDF 的產生?

使用 IronPDF 之類的函式庫,您可以採用索引器來管理和存取儲存在類別中的 HTML 模版,然後將其轉換成 PDF 文件。這種方法簡化了從多個 HTML 來源生成動態 PDF 的過程。

您能舉例說明如何使用 PDF 函式庫與索引器嗎?

當然。您可以建立一個類別,將 HTML 模版存放在陣列中,並使用索引器存取這些模版。然後,使用 PDF 函式庫將這些 HTML 字串渲染為 PDF 文件。例如,一個名為 PdfGenerator 的類別使用索引器來存取 HTML 並產生 PDF。

在 C# 中使用索引器有哪些優點?

C# 中的索引器為存取集合中的元素提供了簡化的語法,讓您的程式碼更直覺、更易讀。它們允許類和結構體表現得像陣列一樣,實現了高效的資料封裝和存取。

索引器如何協助在 C# 中建立動態資料結構?

索引器可讓開發人員使用類似陣列的語法存取和修改集合,從而建立動態資料結構。這在需要彈性管理資料的情況下特別有用,例如動態 PDF 內容產生。

Jacob Mellor, Team Iron 首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技術官,作為 C# PDF 技術的先鋒工程師。作為 Iron Software 核心代碼的原作者,他自開始以來塑造了公司產品架構,與 CEO Cameron Rimington 一起將其轉變為一家擁有超過 50 名員工的公司,為 NASA、特斯拉 和 全世界政府機構服務。

Jacob 持有曼徹斯特大學土木工程一級榮譽学士工程學位(BEng) (1998-2001)。他於 1999 年在倫敦開設了他的第一家軟件公司,並於 2005 年製作了他的首個 .NET 組件,專注於解決 Microsoft 生態系統內的複雜問題。

他的旗艦產品 IronPDF & Iron Suite .NET 庫在全球 NuGet 被安裝超過 3000 萬次,其基礎代碼繼續為世界各地的開發工具提供動力。擁有 25 年的商業經驗和 41 年的編碼專業知識,Jacob 仍專注於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領袖。