C#のインデクサー(開発者向けの仕組み)
C# のインデクサーは、クラスまたは構造体のインスタンスを配列アクセスオペレーター [] を使用してアクセスするための特別なタイプのプロパティです。 インデクサーは"スマート配列"を作成したり、簡略化された構文でデータをカプセル化する際に非常に便利です。 クラスのインスタンスを配列のように使用し、インデックスを介してデータにアクセスできる方法を提供します。 この記事では、実際の例を用いてC#のインデクサーの宣言方法と使用方法を探ります。 また、記事の最後でIronPDFライブラリについても探ります。
インデクサーの基本構文
インデクサーは this キーワードを使用してクラスまたは構造体で宣言されたインスタンスメンバーです。 また、パラメータの型と戻り値の型を指定します。 インデクサーのインスタンスメンバーの一般的な構文は次のようになります。
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 PropertyDefault 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 ClassFriend 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 ClassFriend 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 ブロックはデータを指定されたインデックスに割り当てます。 Here's another example to solidify your understanding:
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 ClassFriend 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 ClassFriend 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; }
}
}Option Strict On
Option Infer 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 ClassOption Strict On
Option Infer 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このコードでは:
- 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 ClassFriend 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 ClassIronPDFとC#インデクサーの使用

IronPDFは、.NETアプリケーションでのPDFの生成、編集、および変換を目的としたC#ライブラリです。 開発者が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 ClassImports 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を作成、操作およびレンダリングするために必要なすべての機能にアクセスできる無料トライアルを利用し、簡単に使用を開始できます。 ソフトウェアをゆっくり探索することができ、満足した場合には $999 からライセンスを利用できます。
ジェイコブ・メラーはIron Softwareの最高技術責任者(CTO)であり、C# PDFテクノロジーを開拓する先見的なエンジニアです。Iron Softwareのコアコードベースを支えるオリジナル開発者として、彼は創業以来、会社の製品アーキテクチャを形成し、CEOのCameron Rimingtonとともに、会社をNASA、Tesla、および世界的な政府機関にサービスを提供する50人以上の会社に変えました。1999年にロンドンで最初のソフトウェアビジネスを開業し、2005年に最初 for .NETコンポーネントを作成した後、Microsoftのエコシステム全体で複雑な問題を解決することを専門としました。