.NET 幫助

C# iList(開發人員如何使用)

Chipego
奇佩戈·卡林达
2024年6月6日
分享:

介紹IList

IList 是 .NET Framework 的 Collections 命名空間的一部分。 它是一種非泛型集合介面,為可以通過其索引單獨訪問的物件集合提供藍圖。 與陣列不同,IList 允許動態數量的物件值元素,這意味著您可以根據需要添加或移除集合中的元素。 它作為 .NET Framework 中所有非泛型列表的基礎介面,提供了一種比數組更靈活地管理物件集合的方法。 在本教程中,我們將學習IList接口和IronPDF C# PDF Library

理解 IList 接口

public interface IList宣告是在 C# 中創建自訂集合的基本部分,這些集合遵循 .NET Framework 的 Collections 命名空間所指定的IList合約。 IList 包含允許訪問集合中元素的屬性和方法,計算元素,並通過添加、插入或移除元素來修改集合。 以下是IList介面中定義的一些關鍵屬性和方法:

  • IsFixedSizeIsReadOnly 這樣的屬性分別指示集合是否為固定大小或唯讀。
  • 像是 Add、void InsertRemoveRemoveAt 這些方法用於修改集合中的元素。 您可以添加、插入和移除元素。
  • IndexOf 方法用於定位元素,而 Item 屬性(或 C# 中的索引子)允許根據索引獲取和設置元素。

公共介面IList的實際應用

為了展示 IList 的運作方式,我們來創建一個簡單的例子。 這個通用版本範例將展示如何宣告一個IList,向其添加項目,並遍歷其內容。

創建和修改IList

首先,我們來看看如何宣告一個IList並向其中添加項目:

using System;
using System.Collections;
class Program
{
    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 interface using count property
        Console.WriteLine($"Number of elements: {myIList.Count}");
        // Access Elements
        foreach (var element in myIList)
        {
            Console.WriteLine(element);
        }
    }
}
using System;
using System.Collections;
class Program
{
    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 interface using count property
        Console.WriteLine($"Number of elements: {myIList.Count}");
        // Access Elements
        foreach (var element in myIList)
        {
            Console.WriteLine(element);
        }
    }
}
Imports System
Imports System.Collections
Friend Class Program
	Private 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 interface using count property
		Console.WriteLine($"Number of elements: {myIList.Count}")
		' Access Elements
		For Each element In myIList
			Console.WriteLine(element)
		Next element
	End Sub
End Class
$vbLabelText   $csharpLabel

在上述範例中,我們使用實作了IList介面的ArrayList類別創建了一個IList實例。 我們添加了不同類型的物件,以展示IList可以保存任何物件。 最後,我們遍歷了這個集合,打印出每個元素。

基於索引的訪問和修改

透過索引存取和修改元素是的一個關鍵特性。 以下IList範例展示了如何做到這一點:

// 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]}");
// 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]}");
' 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)}")
$vbLabelText   $csharpLabel

實作自訂IList

有時候,您可能需要一個繼承自IList的定制集合。 這允許更好地控制元素的儲存、訪問和修改方式。 以下是一個實現 IList 的簡單自定義集合的範例:

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;
// int add
    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();
    }
}
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;
// int add
    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();
    }
}
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
' int add
	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,而ArrayList本身實現了IList。 我們的 CustomCollection 會將調用轉發到底層的 ArrayList,使其能夠像任何其他實現 IList 的集合一樣運作。 此範例演示了創建一個可以透過索引存取、修改(添加、插入或移除項目)並迭代的集合,就像任何實作 IList 的內建 .NET 集合一樣。

使用IList的高級操作

除了基本的添加、删除和存取操作之外,IList 允許進行更複雜的操作和查詢。 例如,檢查集合中是否包含特定物件或尋找物件在集合中的索引,這些操作對某些應用程式可能是必不可少的:

// 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}");
// 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}");
' 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}")
$vbLabelText   $csharpLabel

這些操作在處理對象集合時特別有用,您需要確定特定項目的存在或位置,而無需遍歷整個集合。

IronPDF:C# PDF 庫

C# iList(它如何為開發人員工作):圖 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>來儲存水果名稱的集合。 GeneratePDFFromList 方法然後在這個列表上進行迭代,構建一個包含每個項目的無序列表的 HTML 字串。IronPDF 的 ChromePdfRenderer 將此 HTML 內容轉換為 PDF 文件,隨後將其保存到文件中。

C# iList(開發人員如何運作):圖2 - PDF輸出

結論

C# iList(開發人員的使用方式):圖 3 - 授權

這份入門指南旨在涵蓋 C# 中 IList 的基礎知識和實際應用。 從簡單使用到自定義實作的範例中可以清楚地看出,IList 是 C# 開發人員工具箱中的強大工具。 無論是操作數據集合還是構建自己的集合類型,IList 提供了高效軟件開發所需的功能和靈活性。 IronPDF為感興趣的用戶提供PDF庫的免費試用,許可證起價為$749。

Chipego
奇佩戈·卡林达
軟體工程師
Chipego 擁有天生的傾聽技能,這幫助他理解客戶問題,並提供智能解決方案。他在獲得信息技術理學學士學位後,于 2023 年加入 Iron Software 團隊。IronPDF 和 IronOCR 是 Chipego 專注的兩個產品,但隨著他每天找到新的方法來支持客戶,他對所有產品的了解也在不斷增長。他喜歡在 Iron Software 的協作生活,公司內的團隊成員從各自不同的經歷中共同努力,創造出有效的創新解決方案。當 Chipego 離開辦公桌時,他常常享受讀好書或踢足球的樂趣。
< 上一頁
C# 鏈結串列(開發人員如何使用)
下一個 >
Polly 重試(開發人員如何運作)