.NET 幫助

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

發佈 2024年6月6日
分享:

介紹 IList

IList 是 .NET 框架集合命名空間的一部分。它是一個非泛型集合介面,為可以通過索引單獨訪問的對象集合提供了藍圖。與數組不同, IList 允許動態數量的物件值元素,意味著您可以根據需要新增或移除集合中的元素。它作為所有非泛型列表在 .NET 框架中的基本介面,提供比陣列更靈活的方式來管理物件集合。我們將學習 IList 介面和 IronPDF 庫 在本教程中。

了解 IList 介面

public interface IList 聲明是建立自訂集合的基本部分,這些集合要遵守 .NET 框架的 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
VB   C#

在上述示例中,我們使用 ArrayList 創建了一個 IList 實例,ArrayList 是一個實現了 IList 的類。我們添加了各種不同類型的對象,以演示 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)}")
VB   C#

實現自定義 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
VB   C#

這個 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}")
VB   C#

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

IronPDF:C# PDF 庫

C# iList(它如何為開發人員工作):圖 1 - IronPDF

IronPDF 是一個專為 .NET 開發人員設計的 PDF 庫,允許在 .NET 應用程序內直接創建和操作 PDF 文件。它支持轉換 HTML轉PDF將影像和網頁轉換為 PDF。開發人員可以輕鬆地使用這個庫將 PDF 功能添加到他們的應用程式中。IronPDF 還包括編輯、合併和分割 PDF 文件的功能,為 PDF 操作提供了全面的控制。

代碼範例

這是一個簡單的示例,演示如何使用 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
VB   C#

在此範例中,IList<string> 用來存儲一個水果名稱集合。然後,GeneratePDFFromList方法迭代這個列表,構建一個包含每個項目的無序列表的HTML字符串。IronPDF的ChromePdfRenderer渲染器將這個HTML內容轉換成PDF文檔,隨後將其保存到文件中。

C# iList(開發人員的工作原理):圖2 - PDF輸出

結論

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

這本針對初學者的指南旨在涵蓋C#中IList的基本知識和實際應用。通過從簡單使用到自定義實現的示例,可以清楚地看到IList是C#開發人員工具包中強大的工具。無論你是在操作數據集合還是構建你的集合類型,IList都提供了有效軟體開發所需的功能和靈活性。IronPDF提供了 免費試用 對於感興趣的用戶,授權證書從 $749 起提供。

< 上一頁
C# 鏈結串列(開發人員如何使用)
下一個 >
Polly 重試(開發人員如何運作)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >