跳至頁尾內容
.NET幫助

C# Indexers (How It Works For Developers)

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

在這裡,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;
        }
    }
}
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

在上述程式碼中:

  • 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
    }
}
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陣列提供了簡化的語法,類似於存取陣列中的元素。

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

在此範例中:

  • 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 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

在這段程式碼中:

  • 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]);
        }
    }
}
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

在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.");
    }
}
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所需的所有功能。 您可以慢慢探索該軟體,當您滿意後,可以從$999開始購買授權。

常見問題

什麼是 C# 中的索引器?

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

如何在 C# 中聲明基本索引器?

C# 中的基本索引器使用'這個'關鍵詞和索引器聲明進行聲明。您必須指定參數型別和返回型別。例如:public return_type this[parameter_type index] { get; set; }

'get'和'set'存取器在索引器中的作用是什麼?

索引器中的'get'存取器用於檢索指定索引處的資料,而'set'存取器用於向指定索引分配資料。它們與屬性存取器類似,但用於資料集合。

您可以提供一個 C# 類中索引器的範例嗎?

當然可以。考慮一個名為'程式'的類,具有私有的字串陣列。索引器允許使用整數索引存取此陣列。例如: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。

using C# 索引器有什麼優勢?

C# 的索引器為存取集合中的元素提供了簡化語法,使您的程式碼更直觀且易於閱讀。它們允許類和結構作為陣列進行操作,從而實現高效的資料封裝和存取。

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

索引器允許開發人員通過啟用使用類似陣列的語法存取和修改集合來建立動態資料結構。這在需要靈活管理資料的場景中尤為有用,例如在動態 PDF 內容生成中。

Jacob Mellor,首席技術官 @ Team Iron
首席技術官

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

Jacob擁有曼徹斯特大學的土木工程一等榮譽學士學位(BEng),於1998-2001年之間獲得。在1999年於倫敦創辦他的第一家軟體公司並於2005年建立了他的第一批.NET元組件後,他專注於解決Microsoft生態系統中的複雜問題。

他的旗艦IronPDF和Iron Suite .NET程式庫在全球獲得了超過3000萬次NuGet安裝依據,他的基礎程式碼基繼續支援著世界各地開發者使用的工具。擁有25年的商業經驗和41年的程式設計專業知識,他仍專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron 支援團隊

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