
C# iList(對於開發者的運行原理)
介紹IList
IList 是 .NET Framework 的 Collections 命名空間的一部分。 它是一個非泛型集合介面,為物件集合提供藍圖,允許通過索引單獨存取。 與陣列不同,IList 允許動態的物件值元素數量,這意味著您可以根據需要新增或刪除集合中的元素。 它作為 .NET Framework 中所有非泛型列表的基礎介面,提供比陣列更靈活的物件集合管理方式。 在本教程中,我們將學習 IList 介面和 IronPDF C# PDF 程式庫。
理解IList介面
public interface IList 宣告是建立符合 .NET Framework 的 Collections 命名空間所指定的 IList 契約的自定義集合的基本部分。 IList 包括的屬性和方法使您能夠存取集合中的元素、計算它們,並通過新增、插入或刪除元素來修改集合。 以下是 IList 介面中定義的一些主要屬性和方法:
- 像
IsFixedSize和IsReadOnly這類屬性分別告訴您集合是否是固定大小或唯讀。 - 方法如
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 的集合。 這個範例展示了如何建立一個可以通過索引存取、修改(新增、插入或刪除項目)和迭代的集合,就像任何內建於 .NET 的集合實現 IList 一樣。
使用 IList 進行高級操作
Beyond basic add, remove, and access operations, IList allows for more complex manipulations and queries. 例如,檢查集合中是否包含特定物件或查找集合中的物件索引是某些應用程式所必需的操作:
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 功能。 IronPDF 還包括編輯、合併和拆分 PDF 文件的功能,提供全面的 PDF 操作控制。
IronPDF在HTML到PDF轉換方面表現出色,確保精確保留原始設計和樣式。 它非常適合從基於網路的內容如報告、發票和文件中建立PDF。 IronPDF支持HTML文件、URLs和原始HTML字串,輕鬆生成高品質的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 文件,隨後保存到文件中。

結論
這份對初學者友好的指南旨在涵蓋IList 的基本知識和實際使用。 從簡單使用到自定義實現的範例清楚地表明IList 是 C# 開發者工具箱中的強大工具。 無論您是操作資料集合還是構建自己的集合型別,IList 提供了有效軟體開發所需的功能和靈活性。 IronPDF 為有興趣的使用者提供免費試用其 PDF 程式庫,授權起價為$999。

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。
相關文章


