.NET 帮助

C# iList(它如何为开发人员工作)

发布 2024年六月6日
分享:

IList 简介

IList 是 .NET Framework 的集合命名空间的一部分。它是一个非通用的集合接口,为可通过索引单独访问的对象集合提供了蓝图。与数组不同、 临时清单 允许对象值元素的动态数量,这意味着您可以根据需要从集合中添加或删除元素。它是 .NET Framework 中所有非通用列表的基础接口,提供了一种比数组更灵活的方式来管理对象集合。我们将了解 IList 接口和 IronPDF 库 在本教程中。

了解 IList 接口

公共接口 IList "声明是在 C# 中创建符合 .NET Framework 的集合命名空间指定的 "IList "契约的自定义集合的基本部分。IList包含的属性和方法可以访问集合中的元素、对其进行计数以及通过添加、插入或删除元素来修改集合。下面是IList` 接口定义的一些关键属性和方法:

  • IsFixedSize "和 "IsReadOnly "等属性分别告知集合是固定大小还是只读。
  • 添加"、"插入"、"移除 "和 "移至 "等方法用于修改集合中的元素。您可以添加、插入和删除元素。

  • 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#

在上面的示例中,我们使用实现了 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,这个类本身实现了 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 Library

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 Retry(开发人员如何使用)

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >