跳過到頁腳內容
.NET幫助

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 介面中定義的一些關鍵屬性和方法:

  • 諸如 IsFixedSizeIsReadOnly 之類的屬性分別用於告知集合是固定大小還是唯讀。
  • 諸如 AddInsertRemoveRemoveAt 之類的方法用於修改集合中的元素。 您可以新增、插入或移除元素。
  • 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);
        }
    }
}
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
$vbLabelText   $csharpLabel

在上面的範例中,我們使用 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]}");
    }
}
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
$vbLabelText   $csharpLabel

實作自訂 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
$vbLabelText   $csharpLabel

這個 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
$vbLabelText   $csharpLabel

這些操作在處理物件集合時特別有用,因為您需要在不遍歷整個集合的情況下,確定特定項目的存在或位置。

IronPDF:C# PDF 函式庫

C# iList (How It Works For Developers):圖 1 - IronPDF

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
$vbLabelText   $csharpLabel

程式碼範例

以下是一個簡單的範例,示範如何使用 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
$vbLabelText   $csharpLabel

在這個例子中,使用 IList<string> 來儲存水果名稱的集合。 然後,該方法遍歷此列表,建立一個包含無序列表每個項目的 HTML 字串。 IronPDF 的 ChromePdfRenderer 將此 HTML 內容轉換為 PDF 文件,隨後將其儲存到文件中。

C# iList (How It Works For Developers):圖 2 - PDF 輸出

結論

C# iList (How It Works For Developers):圖 3 - 授權

本入門級指南旨在介紹 C# 中 IList 的基礎知識和實際用途。 從簡單的用法到自訂實現,各種範例都表明 IList 是 C# 開發人員工具包中的強大工具。 無論您是在處理資料集合還是建立集合類型,IList 都提供了有效軟體開發所需的功能和靈活性。 IronPDF 為有興趣的使用者提供免費試用其 PDF 函式庫,許可證價格從 $999 起。

常見問題解答

什麼是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的最新版本。檢查在轉換過程中引發的任何異常以獲取進一步的洞察。

Jacob Mellor, Team Iron 首席技術官
首席技術官

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我