C# iList(對於開發者的運行原理)
IList簡介
IList 是 .NET Framework 的 Collections 命名空間的一部分。 它是一個非一般的集合介面,提供了一個物件集合的藍圖,這些物件可以透過其索引來個別存取。 與陣列不同,IList 允許動態的物件值元素數量,這表示您可以根據需要從集合中新增或移除元素。 它是 .NET Framework 中所有非一般清單的基本介面,提供一種比陣列更靈活的方式來管理物件集合。 在本教程中,我們將學習 IList 介面和 IronPDF C# PDF Library。
瞭解 IList 介面。
public interface IList 聲明是在 C# 中建立自訂集合的基本部分,這些集合遵守 .NET Framework 的 Collections 命名空間指定的 IList 契約。 IList 包含可存取集合中元素、計數元素,以及透過新增、插入或移除元素來修改集合的屬性和方法。 以下是 IList 介面中定義的一些關鍵屬性和方法:
IsFixedSize和IsReadOnly等屬性分別告知集合是固定大小還是唯讀。Add,Insert,Remove, 和RemoveAt等方法用於修改集合中的元素。 您可以新增、插入或移除元素。IndexOf方法用於定位元素,而Item屬性 (或 C# 中的 indexer) 則允許根據元素的索引來取得和設定元素。
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);
}
}
}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在上面的示例中,我們使用實作 IList 的類別 ArrayList 建立了一個 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]}");
}
}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();
}
}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}");
}
}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 檔案、URL 和原始 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");
}
}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);
}
}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 函式庫,並提供 $799 起的授權。
常見問題解答
C# 中的 IList 介面是什麼?
`IList` 介面是 .NET Framework 的 Collections 命名空間的一部分,用於建立可透過索引存取的動態集合。它提供了新增、插入、移除和存取元素的方法,比靜態陣列更具彈性。
如何在 C# 中將 HTML 轉換為 PDF?
您可以使用 IronPDF 的 `RenderHtmlAsPdf` 方法在 C# 中將 HTML 轉換為 PDF。這可讓您將 HTML 字串、檔案或 URL 轉換成高品質的 PDF 文件。
IList 介面有哪些關鍵方法?
`IList` 介面的主要方法包括 `Add`、`Insert`、`Remove`、`RemoveAt` 和 `IndexOf`。這些方法對於動態管理和修改集合內的元素非常重要。
如何在 C# 中建立自訂的 IList?
要在 C# 中建立自訂的「IList」,您可以在類別中實作「IList」介面,覆寫必要的方法和屬性,例如「Add」、「Remove」和「IndexOf」,以自訂集合處理元素的方式。
IronPDF 如何從 HTML 創建 PDF?
IronPDF 使用 `ChromePdfRenderer` 類將 HTML 內容轉換為 PDF。它支援從 HTML 字串、檔案或 URL 的轉換,確保從網頁內容精確地建立 PDF。
您可以從 IList 資料產生 PDF 嗎?
是的,您可以從 IList 生成 PDF,方法是遍歷清單以建構 HTML 字串,然後使用 IronPDF 的 `ChromePdfRenderer` 將 HTML 轉換成 PDF 文件,並使用 `SaveAs` 方法儲存。
IList 支援哪些進階操作?
`IList` 中的進階操作包括使用 `Contains` 檢查集合是否包含特定物件,以及使用 `IndexOf` 找出物件的索引。這些功能有助於有效地管理集合,而不需要手動搜尋元素。
如何排除 C# 中 PDF 生成问题的故障?
如果您在 C# 中生成 PDF 時遇到問題,請確保您的 HTML 內容格式正確,並且您使用的是最新版本的 IronPDF。檢查在轉換過程中所產生的任何異常,以進一步瞭解問題。







