.NET 帮助

C# 主构造函数(对开发人员的工作原理)

发布 2024年一月14日
分享:

在 C# 编程的面向对象环境中,主构造函数的引入为语言的优雅和简洁带来了新的高度。主构造函数与拦截器和集合表达式等功能一样,是 C# 12 中出现的一项强大功能,为声明带参数的构造函数提供了更简洁的语法。您可以在 微软 C# 指南.

在本文中,我们将学习如何高效地使用 C# 12 主构造函数,同时探讨它们的功能、用例以及它们如何改变开发人员处理类初始化的方式。

了解基础知识:C&num 中的构造函数

构造函数在面向对象编程中起着举足轻重的作用,它是初始化对象的蓝图。传统上,C# 开发人员使用默认构造函数或参数化构造函数来设置类的初始状态。然而,主构造函数的引入为 C# 开发的这一重要方面增添了一种更精简的方法。

一级构造函数的本质

C# 中的主构造函数是一种在类声明中直接声明和初始化属性的简洁方法。它简化了属性的定义和赋值过程,提供了一种更具声明性和可读性的语法。

一级建造师的优势

  1. 简洁性: 主要构造函数提供了简洁的语法,减少了模板代码,提高了可读性。

  2. 作用域: 与传统的构造函数不同,主构造函数中的参数在整个类或结构体中都有作用域,因此使用起来非常灵活。

  3. 默认值: 默认参数值简化了对象创建过程,为开发人员提供了更多便利。

声明主构造函数

主构造函数的语法包括直接在类头声明属性。让我们以基本的 "人 "类为例进行说明:

public class Person(string name, int age)
{
    public string Name { get; } = name;
    public int Age { get; } = age
    public override string ToString() => $"Name: {Name}, Age: {Age}";
}
public class Person(string name, int age)
{
    public string Name { get; } = name;
    public int Age { get; } = age
    public override string ToString() => $"Name: {Name}, Age: {Age}";
}
Public Class Person(String name, Integer age)
	Public ReadOnly Property Name() As String = name
	public Integer Age {get;} = age public override String ToString()
	If True Then
		Return $"Name: {Name}, Age: {Age}"
	End If
End Class
VB   C#

在上述代码片段中,Person 类有一个主构造函数,用于初始化实例成员 Name 和实例成员 Age 属性。构造函数参数与类或结构体名称一起声明,在定义公共属性时,参数值会分配给它们。

例 1:二维空间中的不变点

public readonly struct Point(double x, double y)
{
    public double X { get; } = x;
    public double Y { get; } = y;
    public double Magnitude => Math.Sqrt(X * X + Y * Y);
}
public readonly struct Point(double x, double y)
{
    public double X { get; } = x;
    public double Y { get; } = y;
    public double Magnitude => Math.Sqrt(X * X + Y * Y);
}
'INSTANT VB WARNING: VB has no equivalent to the C# readonly struct:
'ORIGINAL LINE: public readonly struct Point(double x, double y)
Public Structure Point(Double x, Double y)
	Public ReadOnly Property X() As Double = x
	Public ReadOnly Property Y() As Double = y
	Public ReadOnly Property Magnitude() As Double
		Get
			Return Math.Sqrt(X * X + Y * Y)
		End Get
	End Property
End Structure
VB   C#

在本例中,Point 结构的主构造函数初始化了 XY 属性,展示了语法的简洁性和表现力。

例 2:带默认设置的可配置记录仪

public class Logger(string filePath = "log.txt", LogLevel level = LogLevel.Info)
{
    private readonly string _filePath = filePath;
    private readonly LogLevel _level = level;
    public void Log(string message)
    {
        // Actual logging implementation using _filePath and _level
    }
}
public class Logger(string filePath = "log.txt", LogLevel level = LogLevel.Info)
{
    private readonly string _filePath = filePath;
    private readonly LogLevel _level = level;
    public void Log(string message)
    {
        // Actual logging implementation using _filePath and _level
    }
}
'INSTANT VB TODO TASK: The following line contains an assignment within expression that was not extracted by Instant VB:
'ORIGINAL LINE: public class Logger(string filePath = "log.txt", LogLevel level = LogLevel.Info)
Public Class Logger(String filePath = "log.txt", LogLevel level = LogLevel.Info)
	Private ReadOnly _filePath As String = filePath
	Private ReadOnly _level As LogLevel = level
	Public Sub Log(ByVal message As String)
		' Actual logging implementation using _filePath and _level
	End Sub
End Class
VB   C#

在这里,Logger 类的主构造函数为 filePathlevel 提供了默认值,使其在保持可配置性的同时,灵活易用。

示例 3:依赖注入

public interface IService
{
    Distance GetDistance();
}
public class ExampleController(IService service) : ControllerBase
{
    public ActionResult<Distance> Get() => service.GetDistance();
}
public interface IService
{
    Distance GetDistance();
}
public class ExampleController(IService service) : ControllerBase
{
    public ActionResult<Distance> Get() => service.GetDistance();
}
Public Interface IService
	Function GetDistance() As Distance
End Interface
Public Class ExampleController(IService service)
	Inherits ControllerBase

	Public Function [Get]() As ActionResult(Of Distance)
		Return service.GetDistance()
	End Function
End Class
VB   C#

主构造函数适合依赖注入方案。在本例中,控制器类指明了它的依赖关系,从而提高了可维护性并方便了单元测试。

例 4:构建几何图形层次结构

public abstract class Shape(double width, double height)
{
    public double Width { get; } = width;
    public double Height { get; } = height;
    public abstract double CalculateArea();
}
public class Rectangle(double width, double height) : Shape(width, height)
{
    public override double CalculateArea() => Width * Height;
}
public class Circle : Shape
{
    public Circle(double radius) : base(radius * 2, radius * 2) { }
    public override double CalculateArea() => Math.PI * Math.Pow(Width / 2, 2);
}
public abstract class Shape(double width, double height)
{
    public double Width { get; } = width;
    public double Height { get; } = height;
    public abstract double CalculateArea();
}
public class Rectangle(double width, double height) : Shape(width, height)
{
    public override double CalculateArea() => Width * Height;
}
public class Circle : Shape
{
    public Circle(double radius) : base(radius * 2, radius * 2) { }
    public override double CalculateArea() => Math.PI * Math.Pow(Width / 2, 2);
}
Public MustInherit Class Shape(Double width, Double height)
	Public ReadOnly Property Width() As Double = width
	Public ReadOnly Property Height() As Double = height
	Public MustOverride Function CalculateArea() As Double
End Class
Public Class Rectangle(Double width, Double height)
	Inherits Shape(width, height)

	Public Overrides Function CalculateArea() As Double
		Return Width * Height
	End Function
End Class
Public Class Circle
	Inherits Shape

	Public Sub New(ByVal radius As Double)
		MyBase.New(radius * 2, radius * 2)
	End Sub
	Public Overrides Function CalculateArea() As Double
		Return Math.PI * Math.Pow(Width / 2, 2)
	End Function
End Class
VB   C#

在本例中,Shape 类中的主构造函数构成了几何形状层次结构的基础。矩形和圆形等子类利用主构造函数进行一致的初始化。Rectangle 类本身声明了主构造函数,并将捕获的主构造函数参数传递给 Shape 类的主参数。Circle 类通过在整个类中定义其构造函数,然后使用 base 关键字将其参数作为默认值传递给 Shape 构造函数,从而展示了其灵活性。

IronPDF 简介

IronPDF 是一个多功能的 C# 库,它能让开发人员毫不费力地创建、处理和转换 PDF 文件。无论您是要生成发票、报告还是其他任何文档,IronPDF 都能让您在 C# 应用程序中直接将 HTML 内容无缝转换为精美、专业的 PDF 文件。

C# 主构造函数(如何为开发人员工作):图 1 - IronPDF 网页

安装 IronPDF:快速入门

要将 IronPDF 整合到 C# 项目中,首先要安装 IronPDF NuGet 软件包。在软件包管理器控制台中执行以下命令:

Install-Package IronPdf

或者,在 NuGet 软件包管理器中找到 "IronPDF",然后继续安装。

C# 主构造函数(开发人员如何使用):图 2 - 在 NuGet 软件包管理器浏览器中搜索 IronPDF 软件包

使用 IronPDF 生成 PDF

使用 IronPDF 创建 PDF 是一个简化的过程。请看下面的例子:

var htmlContent = "<html><body><h1>Hello, IronPDF!</h1></body></html>";
// Create a new PDF document
var pdfDocument = new IronPdf.ChromePdfRenderer();
pdfDocument.RenderHtmlAsPdf(htmlContent).SaveAs("C:/GeneratedDocument.pdf");
var htmlContent = "<html><body><h1>Hello, IronPDF!</h1></body></html>";
// Create a new PDF document
var pdfDocument = new IronPdf.ChromePdfRenderer();
pdfDocument.RenderHtmlAsPdf(htmlContent).SaveAs("C:/GeneratedDocument.pdf");
Dim htmlContent = "<html><body><h1>Hello, IronPDF!</h1></body></html>"
' Create a new PDF document
Dim pdfDocument = New IronPdf.ChromePdfRenderer()
pdfDocument.RenderHtmlAsPdf(htmlContent).SaveAs("C:/GeneratedDocument.pdf")
VB   C#

在本例中,IronPDF 用于将 HTML 内容渲染为 PDF 文档,然后保存到指定位置。有关用 C# 创建和操作 PDF 的更多详情,请访问此完整文档 *教程链接***,如需了解更多信息,请访问此处 文件 page.

C# Primary Constructors:类初始化革命

C# 主构造函数提供了一种声明式的精简方法,可直接在类声明中初始化类属性。让我们来探讨一下这一优雅的功能能否与 IronPDF 无缝集成。

C# Primary Constructors 与 IronPDF 的整合

虽然 C# 主构造函数主要是一种侧重于类初始化的语言功能,但其与 IronPDF 的直接集成可能并不常见。IronPDF 的核心功能在于生成和处理 PDF 文档,而类初始化的具体细节可能与这一工作流程并不直接吻合。

不过,在定义与 IronPDF 配置或数据模型相关的自定义类或结构时,开发人员可以利用 C# 主构造函数。例如,如果您的应用程序需要特定的类结构来管理与 PDF 相关的设置或配置,那么 C# 主构造函数就是简洁地初始化这些类的重要工具。

public class PdfGenerationSettings(string title, bool includeHeader, bool includeFooter)
{
    public string Title { get; } = title;
    public bool IncludeHeader { get; } = includeHeader;
    public bool IncludeFooter { get; } = includeFooter;
    // Additional properties...
}
// Usage with IronPDF
var pdfSettings = new PdfGenerationSettings("My PDF Title", true, false);
var renderOptions = new ChromePdfRenderOptions();
// Apply settings from PdfGenerationSettings
renderOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
renderOptions.MarginTop = 20;
renderOptions.MarginBottom = 20;
renderOptions.MarginLeft = 10;
renderOptions.MarginRight = 10;
renderOptions.Title = pdfSettings.Title ?? string.Empty;
if (pdfSettings.IncludeHeader)
{
    renderOptions.TextHeader = new TextHeaderFooter
    {
        CenterText = "Page {page} of {total-pages}",
        DrawDividerLine = true
    };
}
var pdfDocument = new IronPdf.ChromePdfRenderer();
pdfDocument.RenderingOptions = renderOptions;
pdfDocument.RenderHtmlAsPdf("<html><body><h1>Hello, IronPDF!</h1></body></html>").SaveAs("CustomizedDocument.pdf");
public class PdfGenerationSettings(string title, bool includeHeader, bool includeFooter)
{
    public string Title { get; } = title;
    public bool IncludeHeader { get; } = includeHeader;
    public bool IncludeFooter { get; } = includeFooter;
    // Additional properties...
}
// Usage with IronPDF
var pdfSettings = new PdfGenerationSettings("My PDF Title", true, false);
var renderOptions = new ChromePdfRenderOptions();
// Apply settings from PdfGenerationSettings
renderOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
renderOptions.MarginTop = 20;
renderOptions.MarginBottom = 20;
renderOptions.MarginLeft = 10;
renderOptions.MarginRight = 10;
renderOptions.Title = pdfSettings.Title ?? string.Empty;
if (pdfSettings.IncludeHeader)
{
    renderOptions.TextHeader = new TextHeaderFooter
    {
        CenterText = "Page {page} of {total-pages}",
        DrawDividerLine = true
    };
}
var pdfDocument = new IronPdf.ChromePdfRenderer();
pdfDocument.RenderingOptions = renderOptions;
pdfDocument.RenderHtmlAsPdf("<html><body><h1>Hello, IronPDF!</h1></body></html>").SaveAs("CustomizedDocument.pdf");
Public Class PdfGenerationSettings(String title, Boolean includeHeader, Boolean includeFooter)
	Public ReadOnly Property Title() As String = title
	Public ReadOnly Property IncludeHeader() As Boolean = includeHeader
	Public ReadOnly Property IncludeFooter() As Boolean = includeFooter
	' Additional properties...
End Class
' Usage with IronPDF
Private pdfSettings = New PdfGenerationSettings("My PDF Title", True, False)
Private renderOptions = New ChromePdfRenderOptions()
' Apply settings from PdfGenerationSettings
renderOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4
renderOptions.MarginTop = 20
renderOptions.MarginBottom = 20
renderOptions.MarginLeft = 10
renderOptions.MarginRight = 10
renderOptions.Title = If(pdfSettings.Title, String.Empty)
If pdfSettings.IncludeHeader Then
	renderOptions.TextHeader = New TextHeaderFooter With {
		.CenterText = "Page {page} of {total-pages}",
		.DrawDividerLine = True
	}
End If
Dim pdfDocument = New IronPdf.ChromePdfRenderer()
pdfDocument.RenderingOptions = renderOptions
pdfDocument.RenderHtmlAsPdf("<html><body><h1>Hello, IronPDF!</h1></body></html>").SaveAs("CustomizedDocument.pdf")
VB   C#

在本例中,PDFGenerationSettings 类利用 C# 主构造函数初始化与 PDF 生成设置相关的属性。稍后,可利用这些属性来确定添加哪些渲染选项和跳过哪些选项。输出结果包含使用主构造函数参数设置的页眉文本和标题。

C# 初级构造函数(如何为开发人员工作):图 3 - 上文代码示例的输出 PDF

结论

总之,C# 中的主构造函数为类的初始化提供了一种精致而富有表现力的方法。它们的声明式语法增强了代码的可读性,提高了不变性,并简化了创建具有默认值的对象的过程。无论是定义属性、执行不变性还是使用默认值,一级构造函数都能让开发人员在动态的 C# 编程世界中掌握类初始化的艺术。

虽然 C# 主构造函数与 IronPDF 的直接集成可能不是重点,但这两个元素可以和谐地协同工作。C# 主构造函数提高了类初始化的清晰度和简易性,使其在定义与 IronPDF 工作流相关的结构或配置时非常有价值。

利用 IronPDF 的强大功能生成强大的 PDF,并在类初始化优雅性至关重要的地方使用 C# 主构造函数。在充满活力的 C# 编程世界中,这对充满活力的组合让您能够以创造力和高效率驾驭复杂的文档生成。

IronPDF 提供了 免费试用 及其精简版 许可证 从 $749 开始。

< 前一页
C# 空合并运算符(开发者指南)
下一步 >
C# 双问号(它是如何为开发人员工作的)

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

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