跳過到頁腳內容
.NET幫助

C# 數組長度(對於開發者的運行原理)

陣列是 C# 中的基本資料結構,使開發人員能夠儲存和操作元素集合。 使用陣列時的一個關鍵方面是了解陣列的長度,因為它直接影響我們如何訪問、操作和遍歷陣列元素。 有很多種類型的陣列,可以是多於一個維度的,例如單維陣列、交錯陣列或多維陣列。

在這個全方位指南中,我們將深入探討C# 陣列長度屬性的概念,涵蓋其重要性、確定方式和最佳實踐。 我們還可以使用 C# 陣列和C# PDF 庫 IronPDF建立和查找 PDF 陣列。

1. 什麼是陣列長度?

在 C# 中,陣列的長度代表它可以容納的元素數量。 與一些動態資料結構不同,陣列的大小是初始化時固定的(如三維整數陣列)。 陣列長度是一個關鍵參數,影響各種操作並確保適當的記憶體分配。

2. 確定陣列長度

2.1. 使用 Length 屬性

在 C# 陣列中檢索元素長度的最簡單方法是透過Length屬性。 此屬性是所有陣列實例的固有屬性,且Length屬性返回元素的總數。

int[] numbers = { 1, 2, 3, 4, 5 };
int arrayLength = numbers.Length; // arrayLength will be 5
int[] numbers = { 1, 2, 3, 4, 5 };
int arrayLength = numbers.Length; // arrayLength will be 5
Dim numbers() As Integer = { 1, 2, 3, 4, 5 }
Dim arrayLength As Integer = numbers.Length ' arrayLength will be 5
$vbLabelText   $csharpLabel

2.2. 迴圈迭代

雖然效率低於使用Length屬性變量,但通過迴圈遍歷陣列也可以確定其長度。

int[] numbers = { 1, 2, 3, 4, 5 };
int arrayLength = 0;
foreach (var item in numbers)
{
    arrayLength++;
}
// arrayLength will be 5
int[] numbers = { 1, 2, 3, 4, 5 };
int arrayLength = 0;
foreach (var item in numbers)
{
    arrayLength++;
}
// arrayLength will be 5
Dim numbers() As Integer = { 1, 2, 3, 4, 5 }
Dim arrayLength As Integer = 0
For Each item In numbers
	arrayLength += 1
Next item
' arrayLength will be 5
$vbLabelText   $csharpLabel

需要注意的是,使用Length屬性是最佳選擇,特別是對於大型陣列。

3. 陣列長度與陣列秩

了解陣列長度與陣列秩之間的區別至關重要。 長度指的是一維陣列中的元素總數,如上面的例子所示。 另一方面,秩表示多維陣列的維數。

int[] dimension = new int[5]; // One-dimensional int array, Length: 5, Rank: 1
string[,] dimensionTwo = new string[3, 4]; // Two-dimensional string array, Length: 3 * 4 = 12, Rank: 2
int[] dimension = new int[5]; // One-dimensional int array, Length: 5, Rank: 1
string[,] dimensionTwo = new string[3, 4]; // Two-dimensional string array, Length: 3 * 4 = 12, Rank: 2
Dim dimension(4) As Integer ' One-dimensional int array, Length: 5, Rank: 1
Dim dimensionTwo(2, 3) As String ' Two-dimensional string array, Length: 3 * 4 = 12, Rank: 2
$vbLabelText   $csharpLabel

區分這些概念對於正確的陣列初始化、操作、控制和使用多維陣列和單維陣列的訪問至關重要。

4. 最佳實踐和考慮事項

4.1. 陣列長度和索引

在訪問陣列中的元素時,請確保索引在陣列長度的範圍內。 嘗試訪問超出有效範圍的索引將導致IndexOutOfRangeException

int[] numbers = { 1, 2, 3, 4, 5 };
// Incorrect usage leading to IndexOutOfRangeException
// int value = numbers[10]; // Avoid accessing elements beyond the array length
int[] numbers = { 1, 2, 3, 4, 5 };
// Incorrect usage leading to IndexOutOfRangeException
// int value = numbers[10]; // Avoid accessing elements beyond the array length
Dim numbers() As Integer = { 1, 2, 3, 4, 5 }
' Incorrect usage leading to IndexOutOfRangeException
' int value = numbers[10]; // Avoid accessing elements beyond the array length
$vbLabelText   $csharpLabel

4.2. 動態調整大小

請記住,陣列的長度在初始化後是固定的。 如果需要動態調整大小,請考慮使用其他可以動態增長或縮小的資料結構,例如List

List<int> dynamicList = new List<int>();
dynamicList.Add(1);
dynamicList.Add(2);
// No fixed length; the list can dynamically grow
List<int> dynamicList = new List<int>();
dynamicList.Add(1);
dynamicList.Add(2);
// No fixed length; the list can dynamically grow
Dim dynamicList As New List(Of Integer)()
dynamicList.Add(1)
dynamicList.Add(2)
' No fixed length; the list can dynamically grow
$vbLabelText   $csharpLabel

5. IronPDF 簡介

C# 陣列長度(開發人員如何使用):圖 1 - IronPDF 網頁

IronPDF是一個強大的 C# 庫,使開發人員能夠在其 .NET 應用程式中創建、操作和渲染 PDF 文件。 無論您是在開發 Web 應用程式、桌面應用程式或其他 .NET 專案,IronPDF 簡化了處理 PDF 的過程,提供了一套強大的功能來生成、編輯和處理 PDF 檔案。

IronPDF 的突出功能是其HTML 到 PDF 轉換能力,保持您的布局和樣式不變。 它允許從 Web 內容生成 PDF,非常適合報告、發票和文檔化。 HTML 文件、網址和 HTML 字串可以輕鬆轉換為 PDF。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

使用 IronPDF,開發人員可以無縫地將 PDF 功能整合到他們的應用程式中,允許創建動態和互動式的 PDF 文件。 它支持多種任務,包括由 HTML 生成 PDF,將文本和圖像添加到現有 PDF,從 PDF 中提取數據,等等。

5.1. 安裝 IronPDF

要使用 NuGet 包管理器控制台安裝 IronPDF:

Install-Package IronPdf

此命令將 IronPDF 庫及其依賴項下載並安裝到您的 .NET 專案中。 安裝後,您可以通過導入必要的命名空間開始在應用程式中使用 IronPDF。

5.2. IronPDF:使用 C# 陣列查找 PDF 陣列長度

using IronPdf;
using System;
using System.Linq;

class Program
{
    public static void Main()
    {
        // PDF files to open
        string[] pdfFiles = { "GeneratedPDF_1.pdf", "GeneratedPDF_2.pdf", "GeneratedPDF_3.pdf" };
        PdfDocument[] pdfArray = new PdfDocument[pdfFiles.Length];

        // Counter to keep track of the index
        int index = 0;

        // Loop to open each PDF and extract information
        foreach (string pdfFile in pdfFiles)
        {
            // Load PDF document
            var pdfDocument = PdfDocument.FromFile(pdfFile);
            pdfArray[index++] = pdfDocument; // Add document to array, increment index
        }

        int arrayLength = pdfArray.Length;
        Console.WriteLine("PDF array Length: " + arrayLength);
    }
}
using IronPdf;
using System;
using System.Linq;

class Program
{
    public static void Main()
    {
        // PDF files to open
        string[] pdfFiles = { "GeneratedPDF_1.pdf", "GeneratedPDF_2.pdf", "GeneratedPDF_3.pdf" };
        PdfDocument[] pdfArray = new PdfDocument[pdfFiles.Length];

        // Counter to keep track of the index
        int index = 0;

        // Loop to open each PDF and extract information
        foreach (string pdfFile in pdfFiles)
        {
            // Load PDF document
            var pdfDocument = PdfDocument.FromFile(pdfFile);
            pdfArray[index++] = pdfDocument; // Add document to array, increment index
        }

        int arrayLength = pdfArray.Length;
        Console.WriteLine("PDF array Length: " + arrayLength);
    }
}
Imports IronPdf
Imports System
Imports System.Linq

Friend Class Program
	Public Shared Sub Main()
		' PDF files to open
		Dim pdfFiles() As String = { "GeneratedPDF_1.pdf", "GeneratedPDF_2.pdf", "GeneratedPDF_3.pdf" }
		Dim pdfArray(pdfFiles.Length - 1) As PdfDocument

		' Counter to keep track of the index
		Dim index As Integer = 0

		' Loop to open each PDF and extract information
		For Each pdfFile As String In pdfFiles
			' Load PDF document
			Dim pdfDocument = PdfDocument.FromFile(pdfFile)
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: pdfArray[index++] = pdfDocument;
			pdfArray(index) = pdfDocument ' Add document to array, increment index
			index += 1
		Next pdfFile

		Dim arrayLength As Integer = pdfArray.Length
		Console.WriteLine("PDF array Length: " & arrayLength)
	End Sub
End Class
$vbLabelText   $csharpLabel

此 C# 代碼利用 IronPDF 庫來打開和處理現有的 PDF 文件。 它定義了一個包含 PDF 文件名稱的陣列(pdfFiles)並創建了一個空陣列(pdfArray)來存儲PdfDocument對象。 通過迴圈,它使用 IronPDF 的PdfDocument.FromFile方法打開每個 PDF 文件,為每個文件創建一個PdfDocument對象。然後用這些對象填充pdfArray。 最後,代碼將結果pdfArray的長度列印到控制台,提供有關已處理和存儲的 PDF 的數量的信息。

C# 陣列長度(開發人員如何使用):圖 2 - 先前代碼範例的控制台輸出

結論

本文提供了有關 C# 陣列長度的關鍵概念的全面概述,強調了它們在陣列操作中的重要性。 探討了確定陣列長度的方法、長度與秩的區別以及最佳實踐。

該指南還介紹了IronPDF,一個用於 PDF 處理的強大 C# 庫,並展示了其在打開現有 PDF 文件、創建PdfDocument對象和將其存儲在陣列中的實際應用。 這本簡潔而資訊豐富的指南是尋求掌握陣列操作並利用 IronPDF 高效處理 PDF 任務的 C# 開發人員的寶貴資源。

要進一步探索 IronPDF 的可能性並發揮其全部潛力,開發人員可以利用IronPDF 免費試用授權。 To know more about generating and editing PDFs with IronPDF, visit the IronPDF documentation, and for a tutorial on reading PDF files, visit this IronPDF PDFReader C# Tutorial.

常見問題解答

如何在 C# 中確定陣列的長度?

在 C# 中,您可以使用 Length 屬性來確定陣列的長度。這個屬性返回陣列中元素的總數,這是在初始化期間設置的,而且會保持不變。

C# 中陣列長度和陣列等級有什麼區別?

陣列長度指的是陣列中元素的總數,而陣列等級代表多維陣列中的維度數。例如,二維陣列的等級為 2。

你能在 C# 中改變一個陣列初始化後的長度嗎?

不行,一旦 C# 陣列的長度在初始化期間設置後,就無法更改。如果需要可調整大小的集合,請考慮使用 List 類。

如何在 C# 中避免 IndexOutOfRangeException?

為了避免 IndexOutOfRangeException,始終確保您的索引在陣列範圍內,即從 0 到 array.Length - 1

在使用 C# 操作 PDF 文件中,陣列的實際用途是什麼?

陣列可以用來存儲和處理 C# 中的 PDF 文件集合。通過創建 PdfDocument 對象的陣列,可以使用 IronPDF 這樣的庫提供的方法高效管理多個 PDF。

如何在 .NET 項目中安裝 PDF 操作庫?

要在 .NET 項目中安裝 PDF 操作庫,請使用 NuGet Package Manager。例如,您可以使用命令:Install-Package IronPdf 來安裝 IronPDF。

在 C# 中使用陣列長度的最佳實踐是什麼?

最佳實踐包括使用 Length 屬性提高效率、檢查索引以防止越界錯誤,以及在需要動態調整大小的情況下使用 List

IronPDF 如何促進 C# 中的 HTML 到 PDF 的轉換?

IronPDF 提供了像 RenderHtmlAsPdf 這樣的方法來將 HTML 內容轉換為 PDF 格式,簡化了在 C# 應用程序中從網頁內容生成 PDF 的過程。

Curtis Chau
技術作家

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

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