跳過到頁腳內容
.NET幫助

C# ArrayList(對於開發者的運行原理)

ArrayList 類別是 .NET Framework 集合名稱空間的一部分,旨在儲存一組對象。 它是一個非泛型集合,這意味著它可以儲存任何數據類型的項目。 這一特性使其具有很高的靈活性,但相比於泛型集合,其類型安全性較低。 ArrayList 可以包含重複的元素,並允許動態調整大小,隨著添加或移除有效值而改變。 在本文中,我們將討論 ArrayList 的基本知識以及 IronPDF 鍊庫特點。

ArrayList 的基本知識

ArrayList 實際上是一個非泛型集合,能夠儲存任意數量的任何數據類型的元素,是各種程式開發情境中的多用途選擇。 隨意添加元素或移除項目而不受固定大小的限制是其關鍵特性之一。 ArrayList 透過實現 IList 接口自動調整其大小以容納新元素。 這種動態調整大小對於需要終生變化元素數量的應用程式至關重要。

當您實例化一個 ArrayList 時,您正創建一個可以容納任何對象值的集合,從整數和字串到複雜的自定義對象。 感謝強大增添方法,新增元素到 ArrayList 十分簡單,其中包括 Append 方法,它在集合末尾附加物件值,以及 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 從 ArrayList 中生成 PDF。在 ArrayList 上進行迭代,以將內容編輯為適合 PDF 生成的格式,然後使用 IronPDF 的方法創建和保存 PDF。

使用 IronPDF 與 ArrayLists 有何好處?

IronPDF 允許開發人員輕鬆地將存儲在 ArrayLists 中的數據轉換為 PDF 文件。這對於創建報告或匯出項目列表非常有用,且僅需最少的代碼和最高的效率。

能否向從 ArrayList 生成的 PDF 添加文本和圖像?

可以,使用 IronPDF 您可以自訂 PDF,通過在 ArrayList 中對項目進行迭代來添加文本、圖像和其他內容。

是否可以為在 C# 中從 ArrayList 生成的 PDF 提供安全性?

IronPDF 提供功能來保護您的 PDF 文件。您可以設置密碼和權限來限制對 ArrayList 中生成的 PDFs 的訪問和編輯。

當與 PDF 庫集成時,動態調整大小如何使 ArrayList 受益?

ArrayList 的動態調整大小確保您可以根據需要添加或刪除元素,而無需擔心其容量。這種靈活性在使用諸如 IronPDF 等庫準備數據生成PDF 時非常有益。

使用 IronPDF 對於 C# 開發人員有什麼優勢?

IronPDF 為 C# 開發人員提供了一個強大的工具集,用於生成和操作 PDF 文件。它支持多種功能,如 HTML 到 PDF 的轉換、添加註釋和合併多個 PDF,這使其成為 .NET 應用程序的一個重要庫。

如何在創建 PDF 時處理 ArrayList 中的不同數據類型?

由於 ArrayList 可以存儲任何數據類型,您可以使用 IronPDF 格式化和轉換這些不同的數據類型為一致的 PDF 文件,通過迭代 ArrayList 並應用必要的轉換。

在使用 IronPDF 與 ArrayLists 時有哪些故障排除提示?

確保在轉換為 PDF 之前的 ArrayList 中的數據格式正確。檢查空值和不兼容的數據類型,並使用 IronPDF 調試工具識別和解決在 PDF 生成過程中出現的任何問題。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。