.NET 幫助

C# 初始化陣列(開發人員如何操作)

發佈 2024年3月6日
分享:

陣列是 C# 中的一個基本特徵,允許開發者有效地存儲和操作數據集合。初始化陣列是將初始值分配給其元素的過程。本指南探討了各種技術和最佳實踐。 在 C# 中初始化数组, 提供關於基本和進階陣列初始化情況的見解。

陣列是一組相同類型的元素,存儲在連續的內存位置。在C#中,陣列被用來有效地表示和操作結構化數據。它們提供對單個陣列元素的隨機訪問,使進行排序、搜索和迭代等操作變得容易。

在本文中,我們將看到如何在C#編程語言中初始化一個陣列變量,同時我們也將看到如何使用 IronPDF 創建PDF文檔的陣列 IronPDF.

1. 基本陣列初始化

1.1. 聲明和初始化

初始化陣列最簡單的方法是在創建時聲明它們並分配值。以下是使用方括號初始化整數陣列的範例:

int [] numbers = { 1, 2, 3, 4, 5 };
int [] numbers = { 1, 2, 3, 4, 5 };
Dim numbers() As Integer = { 1, 2, 3, 4, 5 }
VB   C#

在此範例中,名為numbers的陣列被宣告並初始化為五個整數值。C#會根據提供的元素數量自動推斷陣列大小。

1.2. 初始化時指定大小

可以通過明確指定大小來初始化數組,然後再分配值。當數組需要動態調整大小時,這種方法非常有用。例如:

int [] dynamicArray = new int [5];
// The array is initialized with size 5, and the elements are [0, 0, 0, 0, 0]
// Later in the code...
dynamicArray [2] = 42;
// Now the array becomes [0, 0, 42, 0, 0]
int [] dynamicArray = new int [5];
// The array is initialized with size 5, and the elements are [0, 0, 0, 0, 0]
// Later in the code...
dynamicArray [2] = 42;
// Now the array becomes [0, 0, 42, 0, 0]
Dim dynamicArray(4) As Integer
' The array is initialized with size 5, and the elements are [0, 0, 0, 0, 0]
' Later in the code...
dynamicArray (2) = 42
' Now the array becomes [0, 0, 42, 0, 0]
VB   C#

1.3. 預設值

如果陣列被宣告但未顯式初始化,則其元素將根據其資料類型被分配預設值。對於數字類型,預設值為0,對於引用類型,預設值為null。例如:

int [] uninitializedArray = new int [3];
// The elements of uninitializedArray are [0, 0, 0]
int [] uninitializedArray = new int [3];
// The elements of uninitializedArray are [0, 0, 0]
Dim uninitializedArray(2) As Integer
' The elements of uninitializedArray are [0, 0, 0]
VB   C#

2. 使用數值初始化陣列

2.1. 陣列初始化語法

C# 提供了一種稱為陣列初始化的簡潔語法,用於使用特定值初始化陣列。此語法允許您直接在大括號內指定值。例如,您可以像以下這樣初始化字串陣列:

string [] names = { "Alice", "Bob", "Charlie" };
string [] names = { "Alice", "Bob", "Charlie" };
Dim names() As String = { "Alice", "Bob", "Charlie" }
VB   C#

這將建立一個名為 names 的陣列,包含三個元素,每個元素都初始化為一個字串值。

2.2. 多維陣列

除了單維陣列外,C#還支持多維陣列。例如,可以按如下方式初始化一個二維陣列:

int [,] matrix = { { 1, 2, 3 }, { 4, 5, 6 } };
int [,] matrix = { { 1, 2, 3 }, { 4, 5, 6 } };
Dim matrix(,) As Integer = {
	{ 1, 2, 3 },
	{ 4, 5, 6 }
}
VB   C#

這裡,矩陣是一個2x3的整數陣列,已初始化為特定的值。

動態數組初始化

3.1. 使用 Enumerable.Range

對於需要用一系列連續值初始化數組的情況,Enumerable.Range 會很有用。它會在指定範圍內生成一個數字序列。請看以下範例:

int [] rangeArray = Enumerable.Range(1, 5).ToArray();
// The int array is initialized with values [1, 2, 3, 4, 5]
int [] rangeArray = Enumerable.Range(1, 5).ToArray();
// The int array is initialized with values [1, 2, 3, 4, 5]
Dim rangeArray() As Integer = Enumerable.Range(1, 5).ToArray()
' The int array is initialized with values [1, 2, 3, 4, 5]
VB   C#

當您需要一個數字序列而不是逐一指定每個值時,這將特別有用。

C# 初始化陣列(開發者指南):圖 1 - Enumerable.Range 程式範例的控制台輸出

3.2. 使用 LINQ

LINQ (語言集成查詢) 在 C# 中提供強大的查詢功能。您可以使用 LINQ 基於查詢表達式初始化數組。例如:

int [] evenNumbers = (from number in Enumerable.Range(1, 10)
                     where number % 2 == 0
                     select number).ToArray();
// The array is initialized with even values [2, 4, 6, 8, 10]
int [] evenNumbers = (from number in Enumerable.Range(1, 10)
                     where number % 2 == 0
                     select number).ToArray();
// The array is initialized with even values [2, 4, 6, 8, 10]
Dim evenNumbers() As Integer = (
	From number In Enumerable.Range(1, 10)
	Where number Mod 2 = 0
	Select number).ToArray()
' The array is initialized with even values [2, 4, 6, 8, 10]
VB   C#

這種方法更加具有表達力,並允許在陣列初始化過程中進行複雜的篩選和轉換。

C# 初始化陣列(開發人員指南):圖 2 - 前面 LINQ 程式碼範例的控制台輸出

4. 介紹 IronPDF

IronPDF 是一個強大的C#庫,為開發者提供在其.NET應用程式中創建、操作和處理PDF文檔的無縫功能。無論是需要從HTML內容生成PDF、修改現有文檔,還是從PDF中提取數據,IronPDF都提供了一套全面的功能。

IronPDF專精於轉換 HTML轉PDF確保佈局和樣式得到保留。這是一款從網頁內容生成 PDF 的出色工具,例如報告、發票和文檔。HTML 文件、URL 和 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
VB   C#

借由其使用者友好的 API,開發者可以輕鬆地將 PDF 功能整合到他們的 C# 專案中,允許高效且動態地處理與 PDF 相關的任務。IronPDF 以其多功能性和簡單性而突出,使其成為 C# 開發者在處理 PDF 檔案時尋求可靠且靈活解決方案的一個寶貴工具。

4.1. 安裝IronPDF

要使用NuGet Package Manager Console在您的C#項目中安裝IronPDF,請打開Visual Studio,從視圖選單訪問Package Manager Console,並確保選擇了正確的項目。在控制台中運行命令 "Install-Package IronPdf" 並按Enter鍵。

Install-Package IronPdf

允許安裝過程完成,並透過在控制台中的確認訊息以及在方案總管的“參考”部分檢查來驗證成功。IronPDF 現在已準備好在您的 C# 應用程序中使用,提供強大的 PDF 生成和操作功能。

4.2. IronPDF:使用動態PDF初始化創建PDF

using IronPdf;
using System;
class Program
{
    static void Main()
    {
        // Number of PDFs to generate
        int numberOfPDFs = 3;
        // Array to store PdfDocument objects
        PdfDocument [] pdfArray = new PdfDocument [numberOfPDFs];
        // Content for the PDFs
        string [] names = { "Alice", "Bob", "Charlie" };
        string [] ages = { "25", "30", "22" };
        // Instantiate ChromePdfRenderer
        var renderer = new ChromePdfRenderer();
        // Loop to create and customize each PdfDocument in the array
        for (int i = 0; i < numberOfPDFs; i++)
        {
            // Creating dynamic content using string interpolation
            string content = $@"<html>
                                <body>
                                    <h1>Hello, {names [i]}!</h1>
                                    <p>You are {ages [i]} years old.</p>
                                    <p>This is a dynamically generated PDF.</p>
                                </body>
                                </html>";
            // Create a PDF from HTML using ChromePdfRenderer
            pdfArray [i] = renderer.RenderHtmlAsPdf(content);
        }
        // Save each PDF to a file
        for (int i = 0; i < numberOfPDFs; i++)
        {
            pdfArray [i].SaveAs($"GeneratedPDF_{i + 1}.pdf");
        }
        Console.WriteLine("PDFs generated successfully!");
 }
    }
}
using IronPdf;
using System;
class Program
{
    static void Main()
    {
        // Number of PDFs to generate
        int numberOfPDFs = 3;
        // Array to store PdfDocument objects
        PdfDocument [] pdfArray = new PdfDocument [numberOfPDFs];
        // Content for the PDFs
        string [] names = { "Alice", "Bob", "Charlie" };
        string [] ages = { "25", "30", "22" };
        // Instantiate ChromePdfRenderer
        var renderer = new ChromePdfRenderer();
        // Loop to create and customize each PdfDocument in the array
        for (int i = 0; i < numberOfPDFs; i++)
        {
            // Creating dynamic content using string interpolation
            string content = $@"<html>
                                <body>
                                    <h1>Hello, {names [i]}!</h1>
                                    <p>You are {ages [i]} years old.</p>
                                    <p>This is a dynamically generated PDF.</p>
                                </body>
                                </html>";
            // Create a PDF from HTML using ChromePdfRenderer
            pdfArray [i] = renderer.RenderHtmlAsPdf(content);
        }
        // Save each PDF to a file
        for (int i = 0; i < numberOfPDFs; i++)
        {
            pdfArray [i].SaveAs($"GeneratedPDF_{i + 1}.pdf");
        }
        Console.WriteLine("PDFs generated successfully!");
 }
    }
}
Imports IronPdf
Imports System
Friend Class Program
	Shared Sub Main()
		' Number of PDFs to generate
		Dim numberOfPDFs As Integer = 3
		' Array to store PdfDocument objects
		Dim pdfArray(numberOfPDFs - 1) As PdfDocument
		' Content for the PDFs
		Dim names() As String = { "Alice", "Bob", "Charlie" }
		Dim ages() As String = { "25", "30", "22" }
		' Instantiate ChromePdfRenderer
		Dim renderer = New ChromePdfRenderer()
		' Loop to create and customize each PdfDocument in the array
		For i As Integer = 0 To numberOfPDFs - 1
			' Creating dynamic content using string interpolation
			Dim content As String = $"<html>
                                <body>
                                    <h1>Hello, {names (i)}!</h1>
                                    <p>You are {ages (i)} years old.</p>
                                    <p>This is a dynamically generated PDF.</p>
                                </body>
                                </html>"
			' Create a PDF from HTML using ChromePdfRenderer
			pdfArray (i) = renderer.RenderHtmlAsPdf(content)
		Next i
		' Save each PDF to a file
		For i As Integer = 0 To numberOfPDFs - 1
			pdfArray (i).SaveAs($"GeneratedPDF_{i + 1}.pdf")
		Next i
		Console.WriteLine("PDFs generated successfully!")
	End Sub
End Class
}
VB   C#
  1. 我們指定要生成的 PDF 數量 (numberOfPDFs) 並創建一個PdfDocument對象的數組 (pdfArray) 用來儲存生成的 PDF。

  2. 我們使用迴圈來初始化每個陣列元素類型。在迴圈內部,我們使用字串插值為每個 PDF 創建動態內容,包括來自相應陣列的名字和年齡。

  3. 每次迭代我們都會初始化一個新的 PdfDocument 物件,並使用 IronPDF 的 RenderHtmlAsPdf 方法添加 HTML 內容。

  4. 最後,我們將每個 PDF 保存為具有唯一名稱的文件。 (GeneratedPDF_1.pdfGeneratedPDF_2.pdf 等。).

4.2.1. 生成的 PDF 文件

C# 初始化陣列(適用於開發人員的操作方法):圖 3 - 來自上一段代碼示例的輸出 PDF 文件

5. 結論

精通 C# 中多種陣列初始化過程,包括基本方法、陣列初始化語法,以及像 Enumerable.Range 和 LINQ 這樣的動態方法,對於有效的數據操作至關重要。理解陣列長度和秩之間的區別,特別是在多維陣列中,能確保準確處理。

介紹 IronPDF 作為一個強大的 C# 庫,增強了開發人員在 PDF 相關任務中的能力,提供了用戶友好的 API,實現了無縫整合。所提供的範例展示了 IronPDF 在動態生成個性化 PDF 時的高效性,展示了它的多功能性。總體來說,扎實的陣列初始化知識,加上像 IronPDF 這樣的工具,能夠使開發人員創建動態且高效的應用程序,提升他們處理和處理數據的能力。

IronPDF 提供支持和文檔,並附有如何使用此庫的教程。它還提供了一個 免費試用許可證。欲了解有關IronPDF HTML轉換為PDF的詳細教程,請訪問 這裡.

< 上一頁
C# 陣列長度(開發人員如何使用)
下一個 >
C# 結構與類別(開發人員的運作方式)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >