.NET 帮助

C# 析构器(开发者如何使用)

发布 2024年七月1日
分享:

解构者 是帮助您将对象分解为多个值的方法。这与析构函数截然不同,后者用于在对象被垃圾回收之前清理资源。解构器可以让你轻松地从对象中提取值。对于处理复杂数据结构并需要快速、干净地访问对象部分内容的开发人员来说,了解解构器非常有帮助。下面我们将探讨什么是解构器以及它在 IronPDF 库中的用法。

什么是解构器?

C# 中的解构器是在类中定义的,它专门处理将对象分解成若干部分的问题。您可以使用 "public void Deconstruct "方法定义解构器。该方法使用参数来返回对象的组成部分。每个参数对应对象中的一段数据。将其与析构函数区分开来至关重要,后者通常使用 protected override void Finalize 方法定义。

基本解构器示例

考虑一个简单的 Person 类。该类可以有一个解构器,将对象拆分为姓名和年龄。下面是您可以定义它的方法:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public void Deconstruct(out string name, out int age)
    {
        name = this.Name;
        age = this.Age;
    }
}
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public void Deconstruct(out string name, out int age)
    {
        name = this.Name;
        age = this.Age;
    }
}
Public Class Person
	Public Property Name() As String
	Public Property Age() As Integer
	Public Sub Deconstruct(<System.Runtime.InteropServices.Out()> ByRef name As String, <System.Runtime.InteropServices.Out()> ByRef age As Integer)
		name = Me.Name
		age = Me.Age
	End Sub
End Class
VB   C#

在上例中,Person类有一个Deconstruct方法,可以输出NameAge属性。当你想快速将这些值赋值给变量时,这个方法特别有用。

在代码中使用解构器

实际应用

要使用解构器,通常要使用元组解构语法。下面是如何使用 Person 类的解构器:

public static void Main()
{
    Person person = new Person { Name = "Iron Developer", Age = 30 };
    (string name, int age) = person;
    Console.WriteLine($"Name: {name}, Age: {age}");
}
public static void Main()
{
    Person person = new Person { Name = "Iron Developer", Age = 30 };
    (string name, int age) = person;
    Console.WriteLine($"Name: {name}, Age: {age}");
}
Public Shared Sub Main()
	Dim person As New Person With {
		.Name = "Iron Developer",
		.Age = 30
	}
'INSTANT VB TODO TASK: VB has no equivalent to C# deconstruction declarations:
	(String name, Integer age) = person
	Console.WriteLine($"Name: {name}, Age: {age}")
End Sub
VB   C#

该实例中的 public static void Main 方法会创建一个新的 Person,然后使用解构器提取 NameAge。该方法在程序运行时被隐式调用,从而简化了从对象中提取数据的过程。

C# 解构器(如何为开发人员工作):图 1 - C# 解构器的控制台输出:姓名:Iron Developer,年龄:30钢铁开发人员,年龄:30

元组解构

元组解构是从元组中提取值并将其赋值给单个变量的便捷方法。通过这一功能,您可以在单条语句中将元组分解为各个组成部分,从而使代码更简洁、更易读。

示例

下面是如何在 C# 中解构元组:

using System;
public class Program
{
    public static void Main()
    {
        // Create an instance of the Book class
        var book = new Book
        {
            Title = "C# Programming",
            Author = "Jon Skeet",
            Pages = 300
        };

        // Deconstruct the book object to get properties directly
        var (title, author, pages) = DeconstructBook(book);

        // Output the deconstructed properties
        Console.WriteLine($"Title: {title}, Author: {author}, Pages: {pages}");
    }

    // Example of a deconstructor for a Book class
    private static (string title, string author, int pages) DeconstructBook(Book book)
    {
        return (book.Title, book.Author, book.Pages);
    }
}

public class Book
{
    public string Title { get; set; }
    public string Author { get; set; }
    public int Pages { get; set; }
}
using System;
public class Program
{
    public static void Main()
    {
        // Create an instance of the Book class
        var book = new Book
        {
            Title = "C# Programming",
            Author = "Jon Skeet",
            Pages = 300
        };

        // Deconstruct the book object to get properties directly
        var (title, author, pages) = DeconstructBook(book);

        // Output the deconstructed properties
        Console.WriteLine($"Title: {title}, Author: {author}, Pages: {pages}");
    }

    // Example of a deconstructor for a Book class
    private static (string title, string author, int pages) DeconstructBook(Book book)
    {
        return (book.Title, book.Author, book.Pages);
    }
}

public class Book
{
    public string Title { get; set; }
    public string Author { get; set; }
    public int Pages { get; set; }
}
Imports System
Public Class Program
	Public Shared Sub Main()
		' Create an instance of the Book class
		Dim book As New Book With {
			.Title = "C# Programming",
			.Author = "Jon Skeet",
			.Pages = 300
		}

		' Deconstruct the book object to get properties directly
'INSTANT VB TODO TASK: VB has no equivalent to C# deconstruction declarations:
		var(title, author, pages) = DeconstructBook(book)

		' Output the deconstructed properties
		Console.WriteLine($"Title: {title}, Author: {author}, Pages: {pages}")
	End Sub

	' Example of a deconstructor for a Book class
	Private Shared Function DeconstructBook(ByVal book As Book) As (title As String, author As String, pages As Integer)
		Return (book.Title, book.Author, book.Pages)
	End Function
End Class

Public Class Book
	Public Property Title() As String
	Public Property Author() As String
	Public Property Pages() As Integer
End Class
VB   C#

在本例中,Book 类包含三个属性:标题"、"作者 "和 "页数"。解构图书()方法获取图书类的一个实例,并返回一个包含这些属性值的元组。Main "方法中的解构语句()方法将这些值分别赋值给变量 titleauthorpages。这样,您就可以轻松访问各个值,而无需直接引用图书对象。

深入了解解构机原理

主要功能和行为

解构器提供了一种从对象中明确提取信息的方法。必须明确调用它们才能获取数据。这确保了信息可以被直接和立即访问。解构器简化了将对象分解为各个部分的过程。它们对于模式匹配和数值提取特别有用。

继承和解构者

如果基类具有解构器,就可以在派生类中对其进行扩展或重写。这将遵循继承链,允许应用扩展方法,从而进一步定制解构过程。当派生类包含需要提取的额外属性以及从基类继承的属性时,这一点尤其有用。

带有解构器的 IronPDF

IronPDF 是一个.NET 库,可让您使用 C# 轻松创建、编辑和管理 PDF 文件。IronPDF 使用 Chrome 渲染引擎进行转换。它能确保 PDF 文件看起来准确、清晰。它允许开发人员专注于设计 HTML 内容,而不必担心复杂的 PDF 生成细节。IronPDF 支持将 HTML 直接转换为 PDF。它还能将网页表单、URL 和图片转化为 PDF 文档。在编辑方面,您可以为 PDF 添加文本、图片、页眉和页脚。它还能让你用密码和数字签名来保护你的 PDF。

代码示例

下面的代码展示了如何在 C# 中使用 IronPDF 从 HTML 内容生成 PDF,然后使用解构器处理生成的 PDF 文档,以便进行读取属性等进一步操作,而无需调用多个方法或临时变量。这是一种强调生成和解构方面的基本使用模式:

using IronPdf;
public class PdfGenerator
{
    public static void Main()
    {
        License.LicenseKey = "License-Key";

        // Create an instance of the PDF generator
        var renderer = new ChromePdfRenderer();

        // Generate a PDF from HTML
        var pdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello, IronPDF!</h1>");

        // Deconstruct the PDF document to get properties directly
        var (pageCount, author) = DeconstructPdf(pdfDocument);

        // Output the deconstructed properties
        Console.WriteLine($"Page Count: {pageCount}, Author: {author}");
    }

    // Example of a deconstructor for a PdfDocument
    private static (int pageCount, string author) DeconstructPdf(PdfDocument document)
    {
        return (document.PageCount, document.MetaData.Author);
    }
}
using IronPdf;
public class PdfGenerator
{
    public static void Main()
    {
        License.LicenseKey = "License-Key";

        // Create an instance of the PDF generator
        var renderer = new ChromePdfRenderer();

        // Generate a PDF from HTML
        var pdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello, IronPDF!</h1>");

        // Deconstruct the PDF document to get properties directly
        var (pageCount, author) = DeconstructPdf(pdfDocument);

        // Output the deconstructed properties
        Console.WriteLine($"Page Count: {pageCount}, Author: {author}");
    }

    // Example of a deconstructor for a PdfDocument
    private static (int pageCount, string author) DeconstructPdf(PdfDocument document)
    {
        return (document.PageCount, document.MetaData.Author);
    }
}
Imports IronPdf
Public Class PdfGenerator
	Public Shared Sub Main()
		License.LicenseKey = "License-Key"

		' Create an instance of the PDF generator
		Dim renderer = New ChromePdfRenderer()

		' Generate a PDF from HTML
		Dim pdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello, IronPDF!</h1>")

		' Deconstruct the PDF document to get properties directly
'INSTANT VB TODO TASK: VB has no equivalent to C# deconstruction declarations:
		var(pageCount, author) = DeconstructPdf(pdfDocument)

		' Output the deconstructed properties
		Console.WriteLine($"Page Count: {pageCount}, Author: {author}")
	End Sub

	' Example of a deconstructor for a PdfDocument
	Private Shared Function DeconstructPdf(ByVal document As PdfDocument) As (pageCount As Integer, author As String)
		Return (document.PageCount, document.MetaData.Author)
	End Function
End Class
VB   C#

C# 解构器(如何为开发人员工作):图 2 - 显示 PDF 页数和作者信息的控制台输出。

本 C# 示例抽象了从 PDF 文档中获取属性的过程,说明了如何在实际场景中使用解构器来简化代码结构并提高可读性。请记住,IronPDF 本身并不支持解构器;这只是一个用于演示的自定义实现。

结论

总而言之 解构者 是一种功能强大的工具,可让开发人员高效地处理和操作对象中的数据。通过了解如何实现和使用解构器,您可以更有效地管理复杂数据,确保在需要时可以访问对象的所有组件。无论您处理的是简单还是复杂的对象,掌握解构器都将大大提高您的编码效率和管理数据结构的精确度。

IronPDF 起价 749 美元。

< 前一页
Deedle C#(开发人员如何使用它)
下一步 >
Appmetrics C#(开发人员如何使用)

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

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