.NET 도움말 C# Indexers (How It Works For Developers) 커티스 차우 업데이트됨:7월 28, 2025 다운로드 IronPDF NuGet 다운로드 DLL 다운로드 윈도우 설치 프로그램 무료 체험 시작하기 LLM용 사본 LLM용 사본 LLM용 마크다운 형식으로 페이지를 복사하세요 ChatGPT에서 열기 ChatGPT에 이 페이지에 대해 문의하세요 제미니에서 열기 제미니에게 이 페이지에 대해 문의하세요 Grok에서 열기 Grok에게 이 페이지에 대해 문의하세요 혼란 속에서 열기 Perplexity에게 이 페이지에 대해 문의하세요 공유하다 페이스북에 공유하기 트위터에 공유하기 LinkedIn에 공유하기 URL 복사 이메일로 기사 보내기 An indexer in C# is a special type of property that makes instances of a class or struct to be accessed using the array access operator []. Indexers can be very useful in creating "smart arrays" or encapsulating data in a simplified syntax. They provide a way to use instances of a class just like you would use arrays, where you can access data via an index. This article will explore how to declare and use C# indexers with practical examples. And we'll also explore the IronPDF library at the end of the article. Basic Indexer Syntax An indexer is an instance member using the this keyword in a class or struct, followed by the indexer declaration. You also specify the parameter types and the return type. The general syntax for an indexer instance member looks like 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 } } $vbLabelText $csharpLabel Here, return_type is the value type that the indexer will return such as an integer value, and parameter_type is the type of the index, often an int. The get accessor returns the value at the specified index, and the set block code accessor assigns a value to that index. Indexer Declaration and Use We'll examine a basic illustration of implementing an indexer within a C# class. Consider a class Program that encapsulates an array of strings. 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; } } } $vbLabelText $csharpLabel In the above code: The Program class contains a string array named values. The string this[int index] is the indexer declaration, where the int index is the index parameterized property used to access elements of the array. The get accessor returns the indexed value at the specified index, and the set accessor assigns an indexed value to that index. This means you can create an instance of the Program class and access its values array using the indexer, like this: 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 } } $vbLabelText $csharpLabel In this code, you see that the indexer provides a simple syntax for accessing the values array, similar to how you would access elements in an array. Understanding the get and set Accessors The get and set accessors inside the indexer are like block code that allows you to retrieve and assign data similarly to how you would with properties. The main difference is that indexers use an index parameter to work with collections of data rather than individual data members. The get block is responsible for returning the data at the specified index, while the set block assigns data to the specified index. 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; } } } $vbLabelText $csharpLabel In this example: The StudentRecords class has a private string[] studentNames array that holds the names of students. The indexer checks if the index is within the bounds of the array before setting or retrieving the value. An int type Length property provides access to the length of the array. You can use this class in the Main method as follows: 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]); } } } $vbLabelText $csharpLabel Creating a Generic Indexer You can also create generic classes with indexers, allowing your code to handle multiple data types. Here’s a simple example of a generic class with a generic indexer: 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; } } } $vbLabelText $csharpLabel In this code: The GenericClass class defines an indexer that can work with any data type. The this[int index] indexer allows you to access the elements in the array, regardless of the type. You can now use the GenericClass with different data types in the Main method: 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]); } } } $vbLabelText $csharpLabel Using IronPDF with C# Indexer IronPDF is a C# library designed for generating, editing, and converting PDFs in .NET applications. It simplifies working with PDFs for developers to create PDFs from HTML, manipulate PDF files, and handle advanced functionalities such as merging, printing, and adding signatures programmatically. You can leverage IronPDF within your C# programs that utilize indexers to dynamically generate and manage PDF content. For example, suppose you have a class that holds HTML strings, and you want to generate PDFs for each HTML entry using an indexer. This approach streamlines PDF generation while keeping your code organized and intuitive. 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."); } } $vbLabelText $csharpLabel Conclusion C# indexers are a useful feature that helps you to make your classes and structs behave like arrays. By providing simplified syntax and flexible data access, you can create more intuitive and readable code. Whether you’re working with strings, integers, or any other data type, indexers give you the ability to encapsulate your data structure and access it using indices cleanly and efficiently. IronPDF makes it easy to get started with a free trial that gives you access to all the features you need to create, manipulate, and render PDFs. You can take your time exploring the software, and once you're satisfied, licenses are available starting at $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 콘텐츠 생성과 같이 데이터를 유연하게 관리해야 하는 시나리오에서 특히 유용할 수 있습니다. 커티스 차우 지금 바로 엔지니어링 팀과 채팅하세요 기술 문서 작성자 커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다. 커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다. 관련 기사 업데이트됨 12월 11, 2025 Bridging CLI Simplicity & .NET : Using Curl DotNet with IronPDF Jacob Mellor has bridged this gap with CurlDotNet, a library created to bring the familiarity of cURL to the .NET ecosystem. 더 읽어보기 업데이트됨 12월 20, 2025 RandomNumberGenerator C# Using the RandomNumberGenerator C# class can help take your PDF generation and editing projects to the next level 더 읽어보기 업데이트됨 12월 20, 2025 C# String Equals (How it Works for Developers) When combined with a powerful PDF library like IronPDF, switch pattern matching allows you to build smarter, cleaner logic for document processing 더 읽어보기 C# New GUID (How It Works For Developers)C# foreach with index (How It Works...
업데이트됨 12월 11, 2025 Bridging CLI Simplicity & .NET : Using Curl DotNet with IronPDF Jacob Mellor has bridged this gap with CurlDotNet, a library created to bring the familiarity of cURL to the .NET ecosystem. 더 읽어보기
업데이트됨 12월 20, 2025 RandomNumberGenerator C# Using the RandomNumberGenerator C# class can help take your PDF generation and editing projects to the next level 더 읽어보기
업데이트됨 12월 20, 2025 C# String Equals (How it Works for Developers) When combined with a powerful PDF library like IronPDF, switch pattern matching allows you to build smarter, cleaner logic for document processing 더 읽어보기