跳至頁尾內容
開發者更新

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

在 .NET Framework 的集合命名空間中,ArrayList 類別設計用來儲存物件的集合。 它是一個非泛型集合,這意味著它可以容納任何資料型別的項目。 這個功能使其具有高度靈活性,但與泛型集合相比,在型別安全性方面較低。 該 ArrayList 可包含重複元素,並允許在加入或移除有效值時動態調整大小。 在本文中,我們將探討ArrayList的基礎知識及IronPDF 程式庫功能

ArrayList 的基礎知識

ArrayList 本質上是一個非泛型的集合,可以儲存任何資料型別的多個元素,使其成為多種程式設計場景中的多功能選擇。 能夠隨意新增或移除項目而不受固定大小的限制,是其主要特點之一。 ArrayList 自動調整其大小以容納新元素,這一功能是通過其實施 IList 接口實現的。 這種動態調整大小對於需要在其生命週期內包含可變數量元素的應用程式至關重要。

當您實例化一個 ArrayList 時,您是在建立一個可以容納任何物件值的集合,從整數和字串到複雜的自定義物件。 由於有如 Add 方法這類方法的存在,將元素新增到 ArrayList 非常簡單,它將物件值附加到集合的末尾;此外,Insert 方法則將新項目放置在指定索引處,必要時移動現有元素以騰出空間。 這種靈活性使開發人員能夠更有效地管理集合,根據應用程式的需求進行調整。

操作元素

將元素加入 ArrayList 是簡單且直覺的。例如,考慮您正在建立一個包含各種資料型別的集合的情況。 透過 Add 方法,您可以將任何物件附加到 ArrayList,從字串到整數,甚至是其他集合。 ArrayList 的容量會根據需要自動增加,確保始終有空間容納新的物件元素。 這種自動調整大小的優勢明顯優於傳統的陣列,它們需要手動調整大小或建立新陣列以容納更多元素。

ArrayList 還提供了方法,用於在特定位置或索引處插入和移除元素。 Insert 方法允許您將元素新增到指定的位置,有效地使您可以精確地將新項目放置在集合中的任何指定索引處。 同樣地,RemoveRemoveAt 方法可以方便地刪除項目,無論是通過指定要移除的物件還是其在集合中的索引。 這種對 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

移除元素

要移除元素,可以使用 RemoveRemoveAt 方法。 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

在 C# 中使用 ArrayList 的高級範例,涉及的不僅僅是像新增或移除元素這樣的基本操作,還包括更複雜的操作,例如排序、搜索和將 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 轉換為標準陣列。
  • ArrayList 中使用 LINQ 過濾出偶數,展示如何使用 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

在此範例中,我們從建立名為 itemListArrayList 並填充多個字串項目開始。 接下來,我們初始化 IronPDF 的 ChromePdfRenderer 類的一個新實例,將用它將 HTML 內容轉換為 PDF 文件。

輸出

這是 IronPDF 生成的輸出 PDF。

C# ArrayList(開發者如何使用):圖 4 - PDF 輸出

結論

C# ArrayList(開發者如何使用):圖 5 - 授權

ArrayList 是 C# 提供的一個強大集合,用於儲存物件列表。 其動態調整大小的能力和儲存任何型別元素的能力使其在多種應用程式中變得多功能。 然而,為了型別安全性和更好的性能,建議使用泛型集合。 使用 ArrayList 和其方法進行實驗將幫助您理解其用途以及如何整合到應用程式中。

此外,對於有興趣擴展其 C# 功能到 PDF 操作的人,IronPDF 提供了免費試用 .NET PDF 功能來探索其特性。 授權價格從 $999 開始,提供將 PDF 功能整合到 .NET 應用程式中的綜合解決方案。

常見問題

如何在 C# 中將 ArrayList 轉換為 PDF?

您可以使用 IronPDF 從 C# 中的 ArrayList 生成 PDF。遍歷 ArrayList,將內容編譯成適合 PDF 生成的格式,然後使用 IronPDF 的方法來建立和保存 PDF。

using IronPDF 與 ArrayLists 有什麼好處?

IronPDF 允許開發者輕鬆將儲存在 ArrayList 中的資料轉換為 PDF 文件。這對於生成報告或以最少程式碼和最高效率導出項目列表非常有用。

我可以將文字和圖像新增到從 ArrayList 生成的 PDF 中嗎?

是的,使用 IronPDF,您可以在遍歷 ArrayList 中的項目時定制您的 PDF,新增文字、圖像和其他內容。

從 ArrayList 生成的 PDF 在 C# 中可以設置安全性嗎?

IronPDF 提供功能來保護您的 PDF 文件。您可以設定密碼和權限以限制從 ArrayList 中生成的 PDF 的存取和編輯。

動態調整大小對在整合 PDF 程式庫時的 ArrayList 有什麼好處?

ArrayList 的動態調整大小確保您可以根據需要新增或刪除元素,而不必擔心其容量。當使用像 IronPDF 這樣的程式庫準備資料進行 PDF 生成時,這種靈活性是有利的。

using IronPDF 對於 C# 開發者優勢如何?

IronPDF 為 C# 開發者提供了一套強大的工具,用於生成和操作 PDF 文件。它支持多種功能,如 HTML 到 PDF 轉換、新增註釋和合併多個 PDF,這使其成為 .NET 應用程式中的一個必要程式庫。

當建立 PDF 時,我該如何在 ArrayList 中處理不同的資料型別?

由於 ArrayList 可以儲存任何資料型別,您可以使用 IronPDF 格式化和轉換這些多樣資料型別為一個連貫的 PDF 文件,通過遍歷 ArrayList 和應用必要的轉換。

using IronPDF 與 ArrayLists 有哪些故障排除提示?

在轉換為 PDF 之前,確保您的 ArrayList 中的資料格式正確。檢查空值和不相容的資料型別,並使用 IronPDF 的除錯工具來識別和解決 PDF 生成過程中出現的任何問題。

Jacob Mellor,首席技術官 @ Team Iron
首席技術官

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

Jacob擁有曼徹斯特大學的土木工程一等榮譽學士學位(BEng),於1998-2001年之間獲得。在1999年於倫敦創辦他的第一家軟體公司並於2005年建立了他的第一批.NET元組件後,他專注於解決Microsoft生態系統中的複雜問題。

他的旗艦IronPDF和Iron Suite .NET程式庫在全球獲得了超過3000萬次NuGet安裝依據,他的基礎程式碼基繼續支援著世界各地開發者使用的工具。擁有25年的商業經驗和41年的程式設計專業知識,他仍專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話