C# ArrayList(對於開發者的運行原理)
ArrayList 類屬於 .NET Framework 的集合命名空間,設計用來儲存物件集合。 這是一個非一般的集合,意即它可以容納任何資料類型的項目。 此功能使其具有高度彈性,但相較於一般集合,其類型安全性較低。 ArrayList 可包含重複元素,並允許在新增或移除有效值時動態調整大小。 在這篇文章中,我們將討論 ArrayList 的基礎知識和 IronPDF Library Features。
ArrayList 的基礎知識
ArrayList 本質上是一個非一般的集合,能夠儲存任何資料類型的多個元素,使其成為各種程式設計情境的多用途選擇。 能夠不受固定大小的限制,隨意增加元素或移除項目是其主要特色之一。 ArrayList 會自動調整其大小以容納新元素,這項功能是透過實作 IList 介面而實現的。 這種動態大小調整對於需要在生命週期中具有不同元素數量的集合的應用程式而言至關重要。
當您實體化成 ArrayList 時,您所建立的集合可以容納任何物件值,從整數、字串到複雜的自訂物件。 向 ArrayList 中添加元素非常簡單,這要歸功於 Add 和 Insert等方法,Add 可以將物件值追加到集合的末尾,而 Insert則可以在指定索引處放置新項目,並在必要時移動現有元素以騰出空間。 這種靈活性可讓開發人員更有效地管理集合,隨著應用程式的演進而適應其需求。
使用元素工作
向 ArrayList 中添加元素既簡單又直觀。例如,請考慮您正在建立各種類型資料集合的情況。 使用 Add 方法,您可以將任何物件追加到 ArrayList 中,從字串到整數,甚至是其他集合。 ArrayList 的容量會根據需要自動增加,確保總有空間容納新的物件 obj 元素。 相較於需要手動調整大小或建立新陣列以容納更多元素的傳統陣列,這種自動調整大小的功能具有顯著的優勢。
ArrayList 也提供了在特定位置或 int 索引插入和移除元素的方法。 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

本範例示範如何建立新的 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")
移除元素
要移除元素,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
範例:管理 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
本程式碼片段示範如何:
- 使用一組元素初始化 ArrayList。
- 在 ArrayList 中加入單元素和多元素。
- 按值和索引移除元素。
- 排序 ArrayList 以順序排列元素。
- 搜尋元素並找到其索引。
- 將 ArrayList 轉換為標準的陣列。
- 使用 LINQ 與 ArrayList 篩選出偶數,展示如何利用 LINQ 強大的查詢功能橋接非一般的集合。

IronPDF 簡介:C# PDF Library

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
在這個範例中,我們首先建立一個名為 itemList 的 ArrayList 並將數個字串項目填入其中。 接下來,我們初始化 IronPDF 的 ChromePdfRenderer 類的新實例,我們將用它來將 HTML 內容轉換成 PDF 文件。
輸出
以下是 IronPDF 生成的輸出 PDF:

結論

ArrayList 是 C# 提供的功能強大的集合,用來儲存物件清單。 它能夠動態調整大小並儲存任何類型的元素,因此用途廣泛。 但是,為了類型安全和更好的效能,建議使用泛型集合。 實驗使用 ArrayList 及其方法將有助於您瞭解其用途以及如何將其融入您的應用程式。
此外,對於那些有興趣將其 C# 功能擴展到 PDF 操作的人,IronPDF 提供 PDF Functions in .NET 免費試用,以探索其功能。 許可證從 $999 開始,為將 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 生成過程中出現的任何問題。



