跳至页脚内容
.NET 帮助

C# ArrayList(开发人员如何使用)

ArrayList 类是 .NET Framework 的集合命名空间的一部分,旨在存储对象集合。 它是一个非泛型集合,意味着它可以容纳任何数据类型的项目。 这个特性使其非常灵活,但与泛型集合相比,类型安全性较低。 ArrayList 可以包含重复的元素,并允许动态调整大小,因为有效值的添加或删除。 在本文中,我们将讨论 ArrayList 的基础和 IronPDF 库的功能。

ArrayList 的基础

ArrayList 本质上是一个非泛型集合,能够存储任意数据类型的多个元素,使其成为各种编程场景的多才多艺选择。 随意添加元素或删除项目而不受固定大小约束是其关键特性之一。 ArrayList 会自动调整其大小以容纳新元素,这是通过其对 IList 接口的实现实现的。 对于需要在生命周期内具有可变数量元素的集合的应用程序,这种动态调整大小是至关重要的。

当您实例化一个 ArrayList 时,您正在创建一个可以容纳任何对象值的集合,从整数和字符串到复杂的自定义对象。 由于拥有诸如 Add 这样的方法,可以轻松地将元素添加到 ArrayList 中,该方法将对象值附加到集合的末尾,以及 Insert 方法,可以在指定索引处放置一个新项目,必要时移动现有元素以腾出空间。 这种灵活性使开发人员能够更有效地管理集合,根据应用程序的演变需要进行调整。

与元素一起工作

向 ArrayList 添加元素既简单又直观。例如,假设您正在构建各种数据类型的集合。 使用 Add 方法,您可以将任何对象从字符串到整数,甚至是其他集合,附加到您的 ArrayList 中。 ArrayList 的容量会根据需要自动增加,以确保始终有空间用于新对象元素。 这种自动调整大小是传统数组的显著优势,传统数组需要手动调整大小或创建新数组以容纳更多元素。

ArrayList 还提供了在特定位置或整数索引处插入和删除元素的方法。 Insert 方法允许您在指定位置添加元素,有效地使您能够在集合中的任何指定索引处精确地放置新项目。 同样,Remove 和 RemoveAt 方法可以帮助删除项目,可以通过指定要移除的对象或其在集合中的索引来实现。 对 ArrayList 内元素的细粒度控制使其成为管理动态数据的强大工具。

创建和添加元素

要开始使用 ArrayList,您首先需要创建其一个实例。 然后,您可以使用 Add 方法将元素添加到 ArrayList 中,该方法将对象插入到 ArrayList 的末尾。

using System;
using System.Collections;

class Program
{
    // The main entry point of the program
    public static void Main()
    {
        // Create a new ArrayList
        ArrayList myArrayList = new ArrayList();

        // Add elements of different types
        myArrayList.Add("Hello");
        myArrayList.Add(100);

        var item = "World";
        myArrayList.Add(item);

        // Iterate through the ArrayList and print each element
        foreach (var obj in myArrayList)
        {
            Console.WriteLine(obj);
        }
    }
}
using System;
using System.Collections;

class Program
{
    // The main entry point of the program
    public static void Main()
    {
        // Create a new ArrayList
        ArrayList myArrayList = new ArrayList();

        // Add elements of different types
        myArrayList.Add("Hello");
        myArrayList.Add(100);

        var item = "World";
        myArrayList.Add(item);

        // Iterate through the ArrayList and print each element
        foreach (var obj in myArrayList)
        {
            Console.WriteLine(obj);
        }
    }
}
Imports System
Imports System.Collections

Friend Class Program
	' The main entry point of the program
	Public Shared Sub Main()
		' Create a new ArrayList
		Dim myArrayList As New ArrayList()

		' Add elements of different types
		myArrayList.Add("Hello")
		myArrayList.Add(100)

		Dim item = "World"
		myArrayList.Add(item)

		' Iterate through the ArrayList and print each element
		For Each obj In myArrayList
			Console.WriteLine(obj)
		Next obj
	End Sub
End Class
$vbLabelText   $csharpLabel

C# ArrayList (它对开发人员的工作原理):图 1 - 创建 ArrayList 输出

这个例子演示了如何创建一个新的 ArrayList 并向其添加不同类型的元素。 然后使用 foreach 循环遍历 ArrayList,打印每个元素。

插入元素

要在指定索引处插入元素,请使用 Insert 方法,请注意这是一个从零开始的索引系统。

// Insert element at index 1
myArrayList.Insert(1, "Inserted Item");
// Insert element at index 1
myArrayList.Insert(1, "Inserted Item");
' Insert element at index 1
myArrayList.Insert(1, "Inserted Item")
$vbLabelText   $csharpLabel

删除元素

要删除元素,可以用 Remove 和 RemoveAt 方法。 Remove 删除特定对象的第一次出现,而 RemoveAt 删除指定整数索引处的元素。

myArrayList.Remove("Hello"); // Removes the first occurrence of "Hello"
myArrayList.RemoveAt(0);     // Removes the element at index 0
myArrayList.Remove("Hello"); // Removes the first occurrence of "Hello"
myArrayList.RemoveAt(0);     // Removes the element at index 0
myArrayList.Remove("Hello") ' Removes the first occurrence of "Hello"
myArrayList.RemoveAt(0) ' Removes the element at index 0
$vbLabelText   $csharpLabel

示例:管理 ArrayList

创建一个使用 ArrayList 在 C# 中的高级示例,不仅展示了添加或删除元素等基本操作,还展示了更复杂的操作,比如排序、查找和将 ArrayList 转换为其他数据结构。 将以下示例放在 Program.cs 文件中以运行它:

using System;
using System.Collections;
using System.Linq;

class AdvancedArrayListExample
{
    static void Main(string[] args)
    {
        // Initialize an ArrayList with some elements
        ArrayList numbers = new ArrayList() { 5, 8, 1, 3, 2 };

        // Adding elements
        numbers.Add(6); // Add an element to the end
        numbers.AddRange(new int[] { 7, 9, 0 }); // Add multiple elements from a specified collection.

        Console.WriteLine("Initial ArrayList:");
        foreach (int number in numbers)
        {
            Console.Write(number + " ");
        }
        Console.WriteLine("\n");

        // Removing elements
        numbers.Remove(1); // Remove the element 1
        numbers.RemoveAt(0); // Remove the first element

        Console.WriteLine("After Removal:");
        foreach (int number in numbers)
        {
            Console.Write(number + " ");
        }
        Console.WriteLine("\n");

        // Sorting
        numbers.Sort(); // Sort the ArrayList
        Console.WriteLine("Sorted ArrayList:");
        foreach (int number in numbers)
        {
            Console.Write(number + " ");
        }
        Console.WriteLine("\n");

        // Searching
        int searchFor = 5;
        int index = numbers.IndexOf(searchFor); // Find the index of the element
        if (index != -1)
        {
            Console.WriteLine($"Element {searchFor} found at index {index}");
        }
        else
        {
            Console.WriteLine($"Element {searchFor} not found.");
        }
        Console.WriteLine("\n");

        // Converting ArrayList to Array
        int[] numbersArray = (int[])numbers.ToArray(typeof(int));
        Console.WriteLine("Converted Array:");
        foreach (int number in numbersArray)
        {
            Console.Write(number + " ");
        }
        Console.WriteLine("\n");

        // Demonstrate LINQ with ArrayList (Requires System.Linq)
        var evenNumbers = numbers.Cast<int>().Where(n => n % 2 == 0).ToList(); // Assign values to evenNumbers from the filtered results.
        Console.WriteLine("Even Numbers:");
        evenNumbers.ForEach(n => Console.Write(n + " "));
        Console.WriteLine();
    }
}
using System;
using System.Collections;
using System.Linq;

class AdvancedArrayListExample
{
    static void Main(string[] args)
    {
        // Initialize an ArrayList with some elements
        ArrayList numbers = new ArrayList() { 5, 8, 1, 3, 2 };

        // Adding elements
        numbers.Add(6); // Add an element to the end
        numbers.AddRange(new int[] { 7, 9, 0 }); // Add multiple elements from a specified collection.

        Console.WriteLine("Initial ArrayList:");
        foreach (int number in numbers)
        {
            Console.Write(number + " ");
        }
        Console.WriteLine("\n");

        // Removing elements
        numbers.Remove(1); // Remove the element 1
        numbers.RemoveAt(0); // Remove the first element

        Console.WriteLine("After Removal:");
        foreach (int number in numbers)
        {
            Console.Write(number + " ");
        }
        Console.WriteLine("\n");

        // Sorting
        numbers.Sort(); // Sort the ArrayList
        Console.WriteLine("Sorted ArrayList:");
        foreach (int number in numbers)
        {
            Console.Write(number + " ");
        }
        Console.WriteLine("\n");

        // Searching
        int searchFor = 5;
        int index = numbers.IndexOf(searchFor); // Find the index of the element
        if (index != -1)
        {
            Console.WriteLine($"Element {searchFor} found at index {index}");
        }
        else
        {
            Console.WriteLine($"Element {searchFor} not found.");
        }
        Console.WriteLine("\n");

        // Converting ArrayList to Array
        int[] numbersArray = (int[])numbers.ToArray(typeof(int));
        Console.WriteLine("Converted Array:");
        foreach (int number in numbersArray)
        {
            Console.Write(number + " ");
        }
        Console.WriteLine("\n");

        // Demonstrate LINQ with ArrayList (Requires System.Linq)
        var evenNumbers = numbers.Cast<int>().Where(n => n % 2 == 0).ToList(); // Assign values to evenNumbers from the filtered results.
        Console.WriteLine("Even Numbers:");
        evenNumbers.ForEach(n => Console.Write(n + " "));
        Console.WriteLine();
    }
}
Imports Microsoft.VisualBasic
Imports System
Imports System.Collections
Imports System.Linq

Friend Class AdvancedArrayListExample
	Shared Sub Main(ByVal args() As String)
		' Initialize an ArrayList with some elements
		Dim numbers As New ArrayList() From { 5, 8, 1, 3, 2 }

		' Adding elements
		numbers.Add(6) ' Add an element to the end
		numbers.AddRange(New Integer() { 7, 9, 0 }) ' Add multiple elements from a specified collection.

		Console.WriteLine("Initial ArrayList:")
		For Each number As Integer In numbers
			Console.Write(number & " ")
		Next number
		Console.WriteLine(vbLf)

		' Removing elements
		numbers.Remove(1) ' Remove the element 1
		numbers.RemoveAt(0) ' Remove the first element

		Console.WriteLine("After Removal:")
		For Each number As Integer In numbers
			Console.Write(number & " ")
		Next number
		Console.WriteLine(vbLf)

		' Sorting
		numbers.Sort() ' Sort the ArrayList
		Console.WriteLine("Sorted ArrayList:")
		For Each number As Integer In numbers
			Console.Write(number & " ")
		Next number
		Console.WriteLine(vbLf)

		' Searching
		Dim searchFor As Integer = 5
		Dim index As Integer = numbers.IndexOf(searchFor) ' Find the index of the element
		If index <> -1 Then
			Console.WriteLine($"Element {searchFor} found at index {index}")
		Else
			Console.WriteLine($"Element {searchFor} not found.")
		End If
		Console.WriteLine(vbLf)

		' Converting ArrayList to Array
		Dim numbersArray() As Integer = DirectCast(numbers.ToArray(GetType(Integer)), Integer())
		Console.WriteLine("Converted Array:")
		For Each number As Integer In numbersArray
			Console.Write(number & " ")
		Next number
		Console.WriteLine(vbLf)

		' Demonstrate LINQ with ArrayList (Requires System.Linq)
		Dim evenNumbers = numbers.Cast(Of Integer)().Where(Function(n) n Mod 2 = 0).ToList() ' Assign values to evenNumbers from the filtered results.
		Console.WriteLine("Even Numbers:")
		evenNumbers.ForEach(Sub(n) Console.Write(n & " "))
		Console.WriteLine()
	End Sub
End Class
$vbLabelText   $csharpLabel

此代码片段演示如何:

  • 使用一组元素初始化 ArrayList。
  • 向 ArrayList 添加单个和多个元素。
  • 通过值和索引删除元素。
  • 对 ArrayList 进行排序以排序元素。
  • 查找元素并找到其索引。
  • 将 ArrayList 转换为标准数组。
  • 使用 LINQ 与 ArrayList 一起过滤掉偶数,展示如何将非泛型集合与 LINQ 的强大查询功能结合起来。

C# ArrayList (它对开发人员的工作原理):图 2 - ArrayList 输出

IronPDF 简介:C# PDF 库

C# ArrayList (它对开发人员的工作原理):图 3 - IronPDF

IronPDF 是一个功能强大的 C# 库,简化了复杂的 PDF 生成过程,提供了广泛的 PDF 操作功能,包括能够从 HTML 生成 PDF,添加文本和图像,保护文档等等。

将 IronPDF 与 ArrayList 集成

让我们编写一个简单的 C# 程序,创建一个项目的 ArrayList,然后使用 IronPDF 生成一个列出这些项目的 PDF 文档。

using IronPdf;
using System;
using System.Collections;

class PdfCode
{
    static void Main(string[] args)
    {
        // Set your IronPDF license key here
        IronPdf.License.LicenseKey = "Your_License_Key";

        // Create a new ArrayList and add some items
        ArrayList itemList = new ArrayList();
        itemList.Add("Apple");
        itemList.Add("Banana");
        itemList.Add("Cherry");
        itemList.Add("Date");

        // Initialize a new PDF document
        var Renderer = new ChromePdfRenderer();

        // Create an HTML string to hold our content
        string htmlContent = "<h1>Items List</h1><ul>";

        // Iterate over each item in the ArrayList and add it to the HTML string
        foreach (var item in itemList)
        {
            htmlContent += $"<li>{item}</li>";
        }
        htmlContent += "</ul>";

        // Convert the HTML string to a PDF document
        var PDF = Renderer.RenderHtmlAsPdf(htmlContent);

        // Save the PDF to a file
        PDF.SaveAs("ItemList.pdf");

        Console.WriteLine("PDF file 'ItemList.pdf' has been generated.");
    }
}
using IronPdf;
using System;
using System.Collections;

class PdfCode
{
    static void Main(string[] args)
    {
        // Set your IronPDF license key here
        IronPdf.License.LicenseKey = "Your_License_Key";

        // Create a new ArrayList and add some items
        ArrayList itemList = new ArrayList();
        itemList.Add("Apple");
        itemList.Add("Banana");
        itemList.Add("Cherry");
        itemList.Add("Date");

        // Initialize a new PDF document
        var Renderer = new ChromePdfRenderer();

        // Create an HTML string to hold our content
        string htmlContent = "<h1>Items List</h1><ul>";

        // Iterate over each item in the ArrayList and add it to the HTML string
        foreach (var item in itemList)
        {
            htmlContent += $"<li>{item}</li>";
        }
        htmlContent += "</ul>";

        // Convert the HTML string to a PDF document
        var PDF = Renderer.RenderHtmlAsPdf(htmlContent);

        // Save the PDF to a file
        PDF.SaveAs("ItemList.pdf");

        Console.WriteLine("PDF file 'ItemList.pdf' has been generated.");
    }
}
Imports IronPdf
Imports System
Imports System.Collections

Friend Class PdfCode
	Shared Sub Main(ByVal args() As String)
		' Set your IronPDF license key here
		IronPdf.License.LicenseKey = "Your_License_Key"

		' Create a new ArrayList and add some items
		Dim itemList As New ArrayList()
		itemList.Add("Apple")
		itemList.Add("Banana")
		itemList.Add("Cherry")
		itemList.Add("Date")

		' Initialize a new PDF document
		Dim Renderer = New ChromePdfRenderer()

		' Create an HTML string to hold our content
		Dim htmlContent As String = "<h1>Items List</h1><ul>"

		' Iterate over each item in the ArrayList and add it to the HTML string
		For Each item In itemList
			htmlContent &= $"<li>{item}</li>"
		Next item
		htmlContent &= "</ul>"

		' Convert the HTML string to a PDF document
		Dim PDF = Renderer.RenderHtmlAsPdf(htmlContent)

		' Save the PDF to a file
		PDF.SaveAs("ItemList.pdf")

		Console.WriteLine("PDF file 'ItemList.pdf' has been generated.")
	End Sub
End Class
$vbLabelText   $csharpLabel

在这个示例中,我们首先创建一个名为 itemList 的 ArrayList,并填充几个字符串项目。 接下来,我们初始化了 IronPDF 的 ChromePdfRenderer 类的一个新实例,我们将使用它将 HTML 内容转换为 PDF 文档。

输出

这是由 IronPDF 生成的输出 PDF:

C# ArrayList (它对开发人员的工作原理):图 4 - PDF 输出

结论

C# ArrayList (它对开发人员的工作原理):图 5 - 许可

ArrayList 是 C# 提供的一个强大集合,用于存储对象列表。 其动态调整大小和存储任何类型元素的能力使其适合广泛的应用程序。 然而,为了类型安全和更好的性能,推荐使用泛型集合。 尝试使用 ArrayList 及其方法将帮助您了解其使用以及如何将其融入到您的应用程序中。

此外,对于那些有兴趣将其 C# 能力扩展到PDF 操作的用户,IronPDF 提供了一个免费试用 用于 .NET 的 PDF 功能来探索其功能。 许可证从 $799 起,提供了一个集成 PDF 功能到 .NET 应用程序的全面解决方案。

常见问题解答

如何在 C# 中将 ArrayList 转换为 PDF?

您可以使用 IronPDF 从 C# 中的 ArrayList 生成 PDF。遍历 ArrayList,将内容编译成适合 PDF 生成的格式,然后使用 IronPDF 的方法创建和保存 PDF。

使用 IronPDF 与 ArrayLists 的好处是什么?

IronPDF 允许开发人员轻松将存储在 ArrayLists 中的数据转换为 PDF 文档。这对于创建报表或导出项目列表极为有用,代码简单且效率高。

能否向从 ArrayList 生成的 PDF 中添加文本和图像?

是的,使用 IronPDF,您可以自定义您的 PDF,在遍历 ArrayList 项目时添加文本、图像和其他内容。

是否可以保护在 C# 中从 ArrayList 生成的 PDF?

IronPDF 提供功能以保护您的 PDF 文档。您可以设置密码和权限以限制对 ArrayList 中数据生成的 PDF 的访问和编辑。

在集成 PDF 库时,动态调整大小如何有利于 ArrayList?

动态调整 ArrayList 的大小确保您可以根据需要添加或删除元素而不必担心其容量。这种灵活性在使用像 IronPDF 这样的库准备数据以生成 PDF 时是非常有益的。

使用 IronPDF 对 C# 开发人员有什么优势?

IronPDF 为 C# 开发人员提供了一套强大的工具,用于生成和操作 PDF 文档。它支持多种功能,如 HTML 转 PDF 转换、添加注释和合并多个 PDF,使其成为 .NET 应用程序中不可或缺的库。

在创建 PDF 时如何处理 ArrayList 中的不同数据类型?

由于 ArrayList 可以存储任何数据类型,您可以使用 IronPDF 格式化并将这些多样化的数据类型转换为一个统一的 PDF 文档,通过遍历 ArrayList 并应用必要的转换。

使用 IronPDF 与 ArrayLists 的一些故障排除技巧是什么?

确保您 ArrayList 中的数据在转换为 PDF 之前格式正确。检查空值和不兼容的数据类型,并使用 IronPDF 调试工具识别并解决在 PDF 生成过程中出现的任何问题。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。