
C# iList (개발자에게 어떻게 작동하는가)
IList 소개
IList은(는) .NET Framework의 Collections 네임스페이스의 일부입니다. 이는 인덱스를 통해 개별적으로 접근할 수 있는 객체 모음을 위한 설계도를 제공하는 비제네릭 컬렉션 인터페이스입니다. 배열과 달리, IList은 동적 객체 값 요소 수를 허용하며, 필요한 경우 컬렉션에서 요소를 추가하거나 제거할 수 있습니다. .NET Framework의 모든 비제네릭 리스트의 기본 인터페이스 역할을 하며, 배열보다 더 유연한 방식으로 객체의 컬렉션을 관리할 수 있는 방법을 제공합니다. 이 튜토리얼에서는 IList 인터페이스와 IronPDF C# PDF 라이브러리에 대해 배울 것입니다.
IList 인터페이스 이해
public interface IList 선언은 C#의 커스텀 컬렉션 생성을 위한 기본적인 부분이며, 이는 .NET Framework의 Collections 네임스페이스가 명시한 IList 계약을 준수합니다. IList은 컬렉션 요소를 접근하고, 셈을 하고, 요소 추가, 삽입 또는 삭제하여 컬렉션을 수정할 수 있게 해 주는 속성과 메서드를 포함합니다. 다음은 IList 인터페이스에 정의된 주요 속성과 메서드입니다:
IsFixedSize및IsReadOnly과 같은 속성은 컬렉션이 고정 크기인지 또는 읽기 전용인지 알려줍니다.Add,Insert,Remove,RemoveAt와 같은 메서드는 컬렉션 내 요소를 수정할 때 사용됩니다. 요소를 추가하고, 삽입하고, 제거할 수 있습니다.IndexOf메서드는 요소를 찾기 위해 사용되며,Item속성(또는 C#의 인덱서)을 통해 인덱스를 기반으로 요소를 가져오고 설정할 수 있습니다.
IList 인터페이스의 실용적 사용
IList의 작동 방식을 보여주기 위해 간단한 예제를 만들어보겠습니다. 이 예제는 IList을 선언하고, 항목을 추가하고, 내용을 반복하는 방법을 보여줍니다.
IList 생성 및 수정
먼저, IList을 선언하고 항목을 추가하는 방법을 살펴보겠습니다:
using System;
using System.Collections;
class Program
{
static void Main(string[] args)
{
// Creating an IList instance
IList myIList = new ArrayList();
// Adding elements to the IList
myIList.Add("Hello");
myIList.Add(10);
myIList.Add(new object());
// Displaying the number of values in the IList using the Count property
Console.WriteLine($"Number of elements: {myIList.Count}");
// Accessing elements using a loop
foreach (var element in myIList)
{
Console.WriteLine(element);
}
}
}Imports System
Imports System.Collections
Friend Class Program
Shared Sub Main(ByVal args() As String)
' Creating an IList instance
Dim myIList As IList = New ArrayList()
' Adding elements to the IList
myIList.Add("Hello")
myIList.Add(10)
myIList.Add(New Object())
' Displaying the number of values in the IList using the Count property
Console.WriteLine($"Number of elements: {myIList.Count}")
' Accessing elements using a loop
For Each element In myIList
Console.WriteLine(element)
Next element
End Sub
End Class위 예제에서는 ArrayList을 사용하여 IList 인스턴스를 생성하였으며, 이는 IList을 구현한 클래스입니다. 서로 다른 유형의 객체들을 섞어서 추가하여 IList이(가) 모든 객체를 보유할 수 있음을 보여주었습니다. 마지막으로 컬렉션을 반복하며 각 요소를 출력했습니다.
기반 접근 및 수정
인덱스로 요소에 접근하고 수정하는 것은 IList의 핵심 기능입니다. 다음 예제는 어떻게 이러한 작업을 수행할 수 있는지 보여줍니다.
using System;
using System.Collections;
class Program
{
static void Main(string[] args)
{
IList myIList = new ArrayList { "Hello", 10, new object() };
// Accessing an element by index
object value = myIList[1];
Console.WriteLine($"Element at index 1: {value}");
// Modifying an element by index
myIList[1] = 20;
Console.WriteLine($"Modified element at index 1: {myIList[1]}");
}
}Imports System
Imports System.Collections
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim myIList As IList = New ArrayList From { "Hello", 10, New Object() }
' Accessing an element by index
Dim value As Object = myIList(1)
Console.WriteLine($"Element at index 1: {value}")
' Modifying an element by index
myIList(1) = 20
Console.WriteLine($"Modified element at index 1: {myIList(1)}")
End Sub
End Class커스텀 IList 구현
때때로, IList을 상속받는 맞춤형 컬렉션이 필요할 수 있습니다. 이것은 요소의 저장, 접근 및 수정 방법에 대해 더 많은 제어를 가능하게 합니다. 아래는 IList을 구현한 간단한 커스텀 컬렉션의 예제입니다:
using System;
using System.Collections;
public class CustomCollection : IList
{
private ArrayList _innerList = new ArrayList();
public object this[int index]
{
get => _innerList[index];
set => _innerList[index] = value;
}
public bool IsFixedSize => _innerList.IsFixedSize;
public bool IsReadOnly => _innerList.IsReadOnly;
public int Count => _innerList.Count;
public bool IsSynchronized => _innerList.IsSynchronized;
public object SyncRoot => _innerList.SyncRoot;
public int Add(object value)
{
return _innerList.Add(value);
}
public void Clear()
{
_innerList.Clear();
}
public bool Contains(object value)
{
return _innerList.Contains(value);
}
public int IndexOf(object value)
{
return _innerList.IndexOf(value);
}
public void Insert(int index, object value)
{
_innerList.Insert(index, value);
}
public void Remove(object value)
{
_innerList.Remove(value);
}
public void RemoveAt(int index)
{
_innerList.RemoveAt(index);
}
public void CopyTo(Array array, int index)
{
_innerList.CopyTo(array, index);
}
public IEnumerator GetEnumerator()
{
return _innerList.GetEnumerator();
}
}Imports System
Imports System.Collections
Public Class CustomCollection
Implements IList
Private _innerList As New ArrayList()
Default Public Property Item(ByVal index As Integer) As Object Implements IList.Item
Get
Return _innerList(index)
End Get
Set(ByVal value As Object)
_innerList(index) = value
End Set
End Property
Public ReadOnly Property IsFixedSize() As Boolean Implements IList.IsFixedSize
Get
Return _innerList.IsFixedSize
End Get
End Property
Public ReadOnly Property IsReadOnly() As Boolean Implements IList.IsReadOnly
Get
Return _innerList.IsReadOnly
End Get
End Property
Public ReadOnly Property Count() As Integer Implements System.Collections.ICollection.Count
Get
Return _innerList.Count
End Get
End Property
Public ReadOnly Property IsSynchronized() As Boolean Implements System.Collections.ICollection.IsSynchronized
Get
Return _innerList.IsSynchronized
End Get
End Property
Public ReadOnly Property SyncRoot() As Object Implements System.Collections.ICollection.SyncRoot
Get
Return _innerList.SyncRoot
End Get
End Property
Public Function Add(ByVal value As Object) As Integer Implements IList.Add
Return _innerList.Add(value)
End Function
Public Sub Clear() Implements IList.Clear
_innerList.Clear()
End Sub
Public Function Contains(ByVal value As Object) As Boolean Implements IList.Contains
Return _innerList.Contains(value)
End Function
Public Function IndexOf(ByVal value As Object) As Integer Implements IList.IndexOf
Return _innerList.IndexOf(value)
End Function
Public Sub Insert(ByVal index As Integer, ByVal value As Object) Implements IList.Insert
_innerList.Insert(index, value)
End Sub
Public Sub Remove(ByVal value As Object) Implements IList.Remove
_innerList.Remove(value)
End Sub
Public Sub RemoveAt(ByVal index As Integer) Implements IList.RemoveAt
_innerList.RemoveAt(index)
End Sub
Public Sub CopyTo(ByVal array As Array, ByVal index As Integer) Implements System.Collections.ICollection.CopyTo
_innerList.CopyTo(array, index)
End Sub
Public Function GetEnumerator() As IEnumerator Implements System.Collections.IEnumerable.GetEnumerator
Return _innerList.GetEnumerator()
End Function
End Class이 CustomCollection 클래스는 ArrayList을(를) 캡슐화하고 있으며, 이는 IList을 구현한 클래스입니다. 우리의 CustomCollection은 기본이 되는 ArrayList에 대한 호출을 전달하여, 이것이 IList을 구현한 다른 컬렉션과 같이 동작할 수 있도록 합니다. 이 예제는 인덱스로 접근할 수 있고, 수정할 수 있으며(항목 추가, 삽입 또는 삭제), 반복할 수 있는 컬렉션 생성을 보여주며, 이는 IList을 구현한 모든 내장 .NET 컬렉션과 같습니다.
IList과의 고급 작업
기본적인 추가, 제거 및 접근 작업 외에도, IList은 더 복잡한 조작 및 쿼리를 허용합니다. 예를 들어, 컬렉션이 특정 객체를 포함하는지 확인하거나 컬렉션 내에서 객체의 인덱스를 찾는 것은 특정 응용 프로그램에 필수적인 작업일 수 있습니다:
using System;
using System.Collections;
class Program
{
static void Main(string[] args)
{
IList myIList = new ArrayList { "Hello", 10, new object() };
// Check if the IList contains a specific object
bool contains = myIList.Contains(10); // Assuming 10 was added previously
Console.WriteLine($"Contains 10: {contains}");
// Find the index of a specific object
int index = myIList.IndexOf(10);
Console.WriteLine($"Index of 10: {index}");
}
}Imports System
Imports System.Collections
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim myIList As IList = New ArrayList From { "Hello", 10, New Object() }
' Check if the IList contains a specific object
Dim contains As Boolean = myIList.Contains(10) ' Assuming 10 was added previously
Console.WriteLine($"Contains 10: {contains}")
' Find the index of a specific object
Dim index As Integer = myIList.IndexOf(10)
Console.WriteLine($"Index of 10: {index}")
End Sub
End Class이러한 작업은 전체 컬렉션을 반복하지 않고 특정 항목의 존재 여부나 위치를 결정해야 할 때 특히 유용할 수 있습니다.
IronPDF: C# PDF 라이브러리

IronPDF는 .NET 애플리케이션 내에서 PDF 문서를 생성하고 조작할 수 있도록 하는 .NET 개발자를 위한 PDF 라이브러리입니다. HTML을 PDF 문서로, 이미지를 PDF로, 웹 페이지를 PDF로 변환하는 것을 지원합니다. 개발자는 이 라이브러리를 사용하여 애플리케이션에 쉽게 PDF 기능을 추가할 수 있습니다. IronPDF는 PDF 파일을 편집, 병합, 분할하는 기능도 포함하고 있어 PDF 조작에 대한 포괄적인 제어를 제공합니다.
IronPDF는 원래 레이아웃과 스타일을 정확히 보존하여 HTML을 PDF로 변환하는 데 탁월합니다. 보고서, 송장 및 설명서와 같은 웹 기반 콘텐츠에서 PDF를 생성하는 데 완벽합니다. HTML 파일, URL 및 원시 HTML 문자열에 대한 지원으로 IronPDF는 고품질의 PDF 문서를 쉽게 생성합니다.
using IronPdf;
class Program
{
static void Main(string[] args)
{
var renderer = new ChromePdfRenderer();
// 1. Convert HTML String to PDF
var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");
// 2. Convert HTML File to PDF
var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");
// 3. Convert URL to PDF
var url = "http://ironpdf.com"; // Specify the URL
var pdfFromUrl = renderer.RenderUrlAsPdf(url);
pdfFromUrl.SaveAs("URLToPDF.pdf");
}
}Imports IronPdf
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim renderer = New ChromePdfRenderer()
' 1. Convert HTML String to PDF
Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")
' 2. Convert HTML File to PDF
Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")
' 3. Convert URL to PDF
Dim url = "http://ironpdf.com" ' Specify the URL
Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
pdfFromUrl.SaveAs("URLToPDF.pdf")
End Sub
End Class코드 예제
IronPDF 및 IList 인터페이스를 사용하여 문자열 목록으로부터 간단한 PDF 문서를 생성하는 것을 보여주는 간단한 예제가 여기 있습니다:
using IronPdf;
using System.Collections.Generic;
public class PDFGenerator
{
public static void GeneratePDFFromList(IList<string> dataList)
{
// Initialize the HtmlToPdf renderer
var renderer = new ChromePdfRenderer();
// Start building HTML content from the dataList
var htmlContent = "<h1>My Data List</h1><ul>";
foreach (var item in dataList)
{
htmlContent += $"<li>{item}</li>";
}
htmlContent += "</ul>";
// Convert HTML string to PDF
var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
// Save the PDF to a file
pdfDocument.SaveAs("DataList.pdf");
}
}
// Example usage
class Program
{
static void Main(string[] args)
{
License.LicenseKey = "License-Key";
IList<string> myDataList = new List<string> { "Apple", "Banana", "Cherry" };
PDFGenerator.GeneratePDFFromList(myDataList);
}
}Imports IronPdf
Imports System.Collections.Generic
Public Class PDFGenerator
Public Shared Sub GeneratePDFFromList(ByVal dataList As IList(Of String))
' Initialize the HtmlToPdf renderer
Dim renderer = New ChromePdfRenderer()
' Start building HTML content from the dataList
Dim htmlContent = "<h1>My Data List</h1><ul>"
For Each item In dataList
htmlContent &= $"<li>{item}</li>"
Next item
htmlContent &= "</ul>"
' Convert HTML string to PDF
Dim pdfDocument = renderer.RenderHtmlAsPdf(htmlContent)
' Save the PDF to a file
pdfDocument.SaveAs("DataList.pdf")
End Sub
End Class
' Example usage
Friend Class Program
Shared Sub Main(ByVal args() As String)
License.LicenseKey = "License-Key"
Dim myDataList As IList(Of String) = New List(Of String) From {"Apple", "Banana", "Cherry"}
PDFGenerator.GeneratePDFFromList(myDataList)
End Sub
End Class이 예제에서는 여러 과일 이름의 컬렉션을 저장하는 데 IList<string>이(가) 사용되었습니다. 그 후, GeneratePDFFromList 메서드는 이 목록을 순회하며, 각 항목을 비순차 목록에 포함한 HTML 문자열을 작성합니다. IronPDF의 ChromePdfRenderer은 이 HTML 콘텐츠를 PDF 문서로 변환하여 이후 파일에 저장합니다.

결론
이 초보자용 가이드는 C#에서 IList의 기본 사항 및 실용적 사용을 다루고자 했습니다. 단순한 사용법에서 커스텀 구현까지 다양한 예제를 통해, IList은 C# 개발자의 도구상자에 있는 강력한 도구임을 분명히 알 수 있습니다. 데이터 컬렉션을 조작하거나 자신의 컬렉션 유형을 만들 때 IList은 효과적인 소프트웨어 개발에 필요한 기능성과 유연성을 제공합니다. IronPDF는 관심 있는 사용자에게 PDF 라이브러리의 무료 체험판을 제공하며, 라이선스는 $999부터 시작하여 제공됩니다.

제이콥 멜러는 Iron Software의 최고 기술 책임자(CTO)이자 C# PDF 기술을 개척한 선구적인 엔지니어입니다. Iron Software의 핵심 코드베이스를 최초로 개발한 그는 창립 초기부터 회사의 제품 아키텍처를 설계해 왔으며, CEO인 캐머런 리밍턴과 함께 회사를 NASA, 테슬라, 그리고 전 세계 정부 기관에 서비스를 제공하는 50명 이상의 직원을 보유한 기업으로 성장시켰습니다.
관련 기사


