跳過到頁腳內容
.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# 索引器(如何為開發人員工作):圖 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# 索引器(如何為開發人員工作):圖 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 內容生成中。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。