跳過到頁腳內容
.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 屬性提供對陣列長度的存取。

您可以在 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; }
    }
}
Option Strict On



Public Class GenericClass(Of T)
    Private elements As T() = New T(4) {}

    Default Public Property Item(index As Integer) As T
        Get
            Return elements(index)
        End Get
        Set(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

在此程式碼中

  • 泛型類別:該類別定義了一個可以處理任何資料類型的索引器。
  • this[int index] 索引器可讓您存取陣列中的元素,無論其類型為何。

現在您可以在 Main 方法中使用不同的資料類型:

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。 您可以慢慢探索該軟體,一旦您滿意,即可從 $999 開始購買許可證。

常見問題解答

什麼是 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將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

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

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我