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这里,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;
}
}
}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在上述代码中
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在此代码中,您可以看到索引器提供了一种简单的语法来访问values数组,类似于访问数组中的元素。
理解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; }
}
}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在此示例中:
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创建通用索引器
您还可以创建带有索引器的通用类,使您的代码能处理多种数据类型。这是一个具有通用索引器的通用类的简单示例:
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在此代码中:
- 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在 C# 索引器中使用 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
结论
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内容生成,特别有用。








