.NET 帮助

C# 初始化数组(开发人员如何使用)

发布 2024年三月6日
分享:

数组是 C# 的一项基本功能,它允许开发人员高效地存储和处理数据集合。数组初始化是为其元素分配初始值的过程。本指南探讨了数组初始化的各种技术和最佳实践。 *在 C# 中初始化数组***提供了对基本和高级阵列初始化方案的见解。

数组是存储在连续内存位置的同一类型元素的集合。在 C# 中,数组用于高效地表示和处理结构化数据。数组提供了对单个数组元素的随机访问,从而可以轻松执行排序、搜索和迭代等操作。

在本文中,我们将了解如何在 C# 编程语言中初始化数组变量,还将了解如何使用 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#

这里,matrix 是一个 2x3 数组 int,用特定值初始化。

3.动态数组初始化

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 包管理器控制台在 C# 项目中安装 IronPDF,请打开 Visual Studio,从 "视图 "菜单访问 "包管理器控制台",并确保选择了正确的项目。在控制台中运行 "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 数量 (PDF 数量) 并创建一个 PdfDocument 对象数组 (pdfArray) 来存储生成的 PDF 文件。

2.我们使用一个循环来初始化每个数组的元素类型。在循环中,我们使用字符串插值法为每个 PDF 创建动态内容,以包含相应数组中的姓名和年龄。

3.我们为每次迭代初始化一个新的 PdfDocument 对象,并使用 IronPDF 的 RenderHtmlAsPdf 方法添加 HTML 内容。

4.最后,我们将每个 PDF 保存到一个具有唯一名称的文件中 (GeneratedPDF_1.pdf, GeneratedPDF_2.pdf,等等。).

4.2.1.生成 PDF 文件

C# 初始化数组(开发人员如何操作):图 3 - 上一代码示例中输出的 PDF 文件

5.结论

掌握 C# 中各种数组的初始化过程,包括基本方法、数组初始化语法以及 Enumerable.Range 和 LINQ 等动态方法,对于高效的数据处理至关重要。了解数组长度和秩之间的区别,尤其是在多维数组中,可确保准确处理。

介绍 IronPDF 作为一个强大的 C# 库,IronPDF 增强了开发人员执行 PDF 相关任务的能力,提供了用户友好的 API 以实现无缝集成。所提供的示例说明了 IronPDF 在动态生成个性化 PDF 方面的有效性,展示了其多功能性。总之,扎实掌握数组初始化,再加上 IronPDF 这样的工具,开发人员就能创建动态、高效的应用程序,提高有效处理数据的能力。

IronPDF 提供支持和文档,以及如何使用该库的教程。它还提供了 免费试用许可证.有关 IronPDF HTML 转 PDF 的详细教程,请访问 *这里***.

< 前一页
C# 数组长度(开发人员使用方法)
下一步 >
C# 结构体与类(开发人员工作原理)

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >