C# Indeksery (Jak to dziala dla programistow)
Indekser w C# to specjalny typ właściwości, który pozwala na dostęp do instancji klasy lub struktury za pomocą operatora dostępu do tablicy []. Indeksery mogą być bardzo użyteczne przy tworzeniu "inteligentnych tablic" lub enkapsulacji danych w uproszczonej składni. Zapewniają one sposób używania instancji klasy tak, jakby były tablicami, gdzie można uzyskać dostęp do danych poprzez indeks. Ten artykuł przybliży, jak deklarować i używać indeksery C# z praktycznymi przykładami. Na końcu artykułu przyjrzymy się również bibliotece IronPDF.
Podstawowa składnia indeksu
Indekser to element instancji, używający słowa kluczowego this w klasie lub strukturze, po którym następuje deklaracja indeksu. Określa się również typy parametrów oraz typ zwracany. Ogólna składnia dla członka instancji indeksu wygląda następująco:
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
Tutaj return_type to typ wartości, który indeks będzie zwracał, jak np. wartość całkowita, a parameter_type to typ indeksu, często int. Akcesor get zwraca wartość pod określonym indeksem, a blok kodu akcesora set przypisuje wartość do tego indeksu.
Deklaracja i użycie indeksu
Zbadamy podstawowy przykład implementacji indeksu w klasie C#. Rozważ klasę Program, która enkapsuluje tablicę ciągów znakowych.
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
W powyższym kodzie:
- Klasa
Programzawiera tablicę ciągów znakowych o nazwievalues. string this[int index]to deklaracja indeksu, gdzieint indexto zindeksowana właściwość parametryzowana używana do dostępu do elementów tablicy.- Akcesor
getzwraca zindeksowaną wartość pod określonym indeksem, a akcesorsetprzypisuje zindeksowaną wartość do tego indeksu.
Oznacza to, że można utworzyć instancję klasy Program i uzyskać dostęp do jej tablicy values używając indeksu, jak poniżej:
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
W tym kodzie widać, że indeks zapewnia prostą składnię do dostępu do tablicy values, podobnie jak przy dostępie do elementów tablicy.
Zrozumienie akcesorów get i set
Akcesory get i set wewnątrz indeksu są jak blok kodu, który pozwala pobierać i przypisywać dane podobnie jak przy użyciu właściwości. Główna różnica polega na tym, że indeksy używają parametru indeksowego do pracy z kolekcjami danych, a nie z poszczególnymi częściami danych.
Blok get odpowiada za zwracanie danych pod określonym indeksem, podczas gdy blok set przypisuje dane do określonego indeksu. Oto kolejny przykład, aby utrwalić zrozumienie:
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
W tym przykładzie:
- Klasa
StudentRecordsma prywatną tablicęstring[] studentNames, która przechowuje imiona studentów. - Indekser sprawdza, czy indeks jest w zakresie tablicy przed ustawieniem lub pobraniem wartości.
- Właściwość typu
intLengthzapewnia dostęp do długości tablicy.
Można użyć tej klasy w metodzie Main w następujący sposób:
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
Tworzenie generycznego indeksu
Można również tworzyć klasy generyczne z indeksami, pozwalające aby kod obsługiwał wiele typów danych. Oto prosty przykład klasy generycznej z generycznym indeksem:
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
W tym kodzie:
- Klasa GenericClass definiuje indeks, który może pracować z dowolnym typem danych.
- Indeksowanie
this[int index]pozwala na dostęp do elementów tablicy, niezależnie od typu.
Teraz możesz używać GenericClass z różnymi typami danych w metodzie 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
Używanie IronPDF z indekserem C

IronPDF to biblioteka C# zaprojektowana do generowania, edycji i konwersji PDF w aplikacjach .NET. Upraszcza ona pracę z PDF dla programistów do tworzenia PDF z HTML, manipulacji plikami PDF i obsługi zaawansowanych funkcji, takich jak łączenie, drukowanie i dodawanie podpisów programowo.
Można wykorzystać IronPDF w ramach programów C#, które używają indeksów do dynamicznego generowania i zarządzania zawartością PDF. Na przykład, wyobraź sobie, że masz klasę, która przechowuje ciągi HTML i chcesz generować PDF dla każdego wpisu HTML przy użyciu indeksu. Podejście to usprawnia generowanie PDF, utrzymując jednocześnie kod zorganizowany i intuicyjny.
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

Wnioski
Indeksery C# to przydatna funkcja, ktora pomaga, by Twoje klasy i struktury zachowywały sie jak tablice. Dostarczając uproszczoną składnię i elastyczny dostęp do danych, możesz tworzyć bardziej intuicyjny i czytelny kod. Niezależnie od tego, czy pracujesz z ciągami znaków, liczbami całkowitymi czy jakimkolwiek innym typem danych, indeksatory dają Ci możliwość hermetyzacji struktury danych i uzyskiwania do niej dostępu za pomocą indeksów w przejrzysty i wydajny sposób.
IronPDF ułatwia rozpoczęcie pracy dzięki bezpłatnej wersji próbnej, która zapewnia dostęp do wszystkich funkcji potrzebnych do tworzenia, edycji i renderowania plików PDF. Możesz poświęcić czas na badanie oprogramowania, a kiedy będziesz zadowolony, licencje są dostępne od $799.
Często Zadawane Pytania
Czym jest indeksator w C#?
Indeksator w C# to specjalny typ właściwości, który pozwala na dostęp do instancji klasy lub struktury za pomocą operatora dostępu do tablic []. Umożliwia to używanie instancji klasy tak samo, jak tablic.
Jak zadeklarować podstawowy indeksator w C#?
Podstawowy indeksator w C# deklaruje się używając słowa kluczowego 'this' wraz z deklaracją indeksatora. Należy określić typy parametrów oraz typ zwracany. Na przykład: public return_type this[parameter_type index] { get; set; }.
Jaki jest cel akcesorów 'get' i 'set' w indeksatorze?
Akcesor 'get' w indeksatorze służy do pobierania danych w określonym indeksie, natomiast akcesor 'set' służy do przypisywania danych do określonego indeksu. Działają one podobnie jak akcesory właściwości, ale są używane dla kolekcji danych.
Czy możesz podać przykład indeksatora w klasie C#?
Oczywiście. Rozważ klasę 'Program' z prywatną tablicą stringów. Indeksator pozwala na dostęp do tej tablicy za pomocą indeksu całkowitego. Na przykład: public string this[int index] { get { return values[index]; } set { values[index] = value; } }.
Jak stworzyć generyczny indeksator w C#?
Generyczny indeksator w C# można stworzyć w ramach klasy ogólnej. Na przykład, klasa GenericClass zawiera indeksator, który może obsługiwać dowolny typ danych. Indeksator jest zadeklarowany jako public T this[int index] { get; set; }.
Jak można wykorzystać indeksatory w C#, aby usprawnić generowanie PDF?
Używając biblioteki takiej jak IronPDF, można wykorzystać indeksatory do zarządzania i dostępu do szablonów HTML przechowywanych w klasie, które następnie są konwertowane na dokumenty PDF. To podejście upraszcza proces generowania dynamicznych PDF z wielu źródeł HTML.
Czy możesz podać przykład użycia biblioteki PDF z indeksatorem?
Z pewnością. Możesz stworzyć klasę, która przechowuje szablony HTML w tablicy i użyć indeksatora do dostępu do tych szablonów. Następnie, użyć biblioteki PDF do renderowania tych łańcuchów HTML jako dokumentów PDF. Na przykład, klasa PdfGenerator używa indeksatora do dostępu do HTML i generowania PDF.
Jakie są zalety używania indeksatorów w C#?
Indeksatory w języku C# zapewniają uproszczoną składnię dostępu do elementów w kolekcji, dzięki czemu kod staje się bardziej intuicyjny i czytelny. Pozwalają one klasom i strukturom zachowywać się jak tablice, umożliwiając wydajną enkapsulację danych i dostęp do nich.
W jaki sposób indeksatory mogą pomóc w tworzeniu dynamicznych struktur danych w języku C#?
Indeksatory pozwalają programistom tworzyć dynamiczne struktury danych, umożliwiając dostęp do kolekcji i ich modyfikację przy użyciu składni podobnej do tablicowej. Może to być szczególnie przydatne w sytuacjach, w których dane muszą być zarządzane w sposób elastyczny, na przykład podczas dynamicznego generowania treści PDF.




