.NET 帮助 C# Primary Constructor(开发者如何使用) Curtis Chau 已更新:六月 20, 2025 Download IronPDF NuGet 下载 DLL 下载 Windows 安装程序 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article 在 C# 编程的面向对象环境中,主构造函数的引入为语言带来了新的优雅和简洁。 主构造函数与拦截器和集合表达式等功能一起,在 C# 12 中作为一个强大的特性出现,为使用参数声明构造函数提供了更简洁的语法。 您可以在 微软 C# 指南上深入探索主构造函数。 在本文中,我们将学习如何高效使用 C# 12 主构造函数,同时探索其功能、用例以及它们如何改变开发人员设置类初始化的方式。 理解基础知识:C# 中的构造函数 构造函数在面向对象编程中起着至关重要的作用,是初始化对象的蓝图。 传统上,C# 开发人员使用默认构造函数或参数化构造函数来设置类的初始状态。 然而,主构造函数的引入为这个 C# 开发的重要方面提供了一种更精简的方法。 主构造函数的本质 在 C# 中,主构造函数是一种直接在类声明中声明和初始化属性的简洁方法。 它简化了定义和分配属性值的过程,提供了更具声明性和可读性的语法。 主构造函数的优势 简洁性:主构造函数提供简洁的语法,减少样板代码并增强可读性。 作用域:与传统构造函数不同的是,主构造函数中的参数在整个类或结构体中都处于作用域,使其使用更灵活。 默认值:默认参数值简化了对象创建,对开发人员来说更加方便。 声明主构造函数 主构造函数的语法涉及在类头中直接声明属性。 让我们以一个基本的 Person 类为例: 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 ReadOnly Property Age() As Integer = age Public Overrides Function ToString() As String Return $"Name: {Name}, Age: {Age}" End Function End Class $vbLabelText $csharpLabel 在上面的代码片段中,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 $vbLabelText $csharpLabel 在此示例中,Point 结构体的主构造函数初始化 X 和 Y 属性,展示了语法如何简明而富有表现力。 示例 2:具有默认设置的可配置 Logger 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 $vbLabelText $csharpLabel 在此示例中,Logger 类的主构造函数为 filePath 和 level 提供了默认值,做到灵活易用,同时保持可配置性。 示例 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 $vbLabelText $csharpLabel 主构造函数适用于依赖注入场景。 在此示例中,控制器类表明其依赖关系,增强了可维护性,并促进了单元测试。 示例 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 $vbLabelText $csharpLabel 在此示例中,Shape 类的主构造函数构成了几何形状层次结构的基础。 像 Rectangle 和 Circle 等子类利用主构造函数实现一致的初始化。 Rectangle 类本身声明了主构造函数,并将捕获的主构造函数参数传递给 Shape 类的主参数。 Circle 类通过在整个类内定义构造函数,然后使用 base 关键字将其参数作为默认值传递给 Shape 构造函数,展示了灵活性。 IronPDF 简介 IronPDF 是一个多功能的 C# 库,使开发人员能够轻松创建、操作和转换 PDF 文件。 无论是生成发票、报告还是其他文档,IronPDF 都允许您在 C# 应用程序中无缝地将 HTML 内容转换为优雅的专业 PDF。 IronPDF 是开发人员的一个方便工具,让他们把网页、URL 和 HTML 转换为 PDF。 最好的部分是,生成的 PDF 看起来和原始网页一模一样,所有的格式和样式都得以保留。 它非常适合从网页内容创建像报告和发票这样的 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:快速入门 在您的包管理器控制台中执行以下命令: 或者,在NuGet包管理器中找到“IronPDF”并继续安装。 Install-Package IronPdf 使用IronPDF创建PDF是一个简单的过程。 使用 IronPDF 生成 PDF 使用 IronPDF 创建 PDF 是一个简化的过程。 在此示例中,IronPDF用于将HTML内容渲染为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") $vbLabelText $csharpLabel 请访问此 探索IronPDF代码示例 资源,获取更多创建PDF文档的方法。 For more details on creating and manipulating PDFs in C#, please visit this complete tutorial link, and to explore more please visit this documentation page. C# 主构造函数:类初始化的革命 C# 主构造函数提供了一种声明性和简化的方法,直接在类声明中初始化类属性。 让我们探讨一下这个优雅的特性是否可以无缝集成到 IronPDF 中。 C# 主构造函数与 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 { PaperSize = IronPdf.Rendering.PdfPaperSize.A4, MarginTop = 20, MarginBottom = 20, MarginLeft = 10, MarginRight = 10, Title = pdfSettings.Title }; // Apply settings from PdfGenerationSettings 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 { PaperSize = IronPdf.Rendering.PdfPaperSize.A4, MarginTop = 20, MarginBottom = 20, MarginLeft = 10, MarginRight = 10, Title = pdfSettings.Title }; // Apply settings from PdfGenerationSettings 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 With { .PaperSize = IronPdf.Rendering.PdfPaperSize.A4, .MarginTop = 20, .MarginBottom = 20, .MarginLeft = 10, .MarginRight = 10, .Title = pdfSettings.Title } ' Apply settings from PdfGenerationSettings 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") $vbLabelText $csharpLabel 在此示例中,PdfGenerationSettings 类利用 C# 主构造函数初始化与 PDF 生成设置相关的属性,这些属性可用于确定哪些渲染选项要添加、哪些要跳过。输出包含头文本和标题,因为它是使用主构造函数参数设置的。 结论 总之,C# 中的主构造函数提供了一种精致的和富有表现力的类初始化方法。 它们的声明性语法增强了代码可读性,促进了不变性,并简化了创建带有默认值的对象的过程。 无论您是在定义属性、强制不变性、或者采用默认值,主构造函数赋予开发人员掌握 C# 编程动态世界中类初始化的艺术。 虽然 C# 主构造函数与 IronPDF 之间的直接集成可能不是重点,但这两个元素可以和谐工作。 C# 主构造函数提升了类初始化的清晰性和简洁性,使其在定义与 IronPDF 工作流程相关的结构或配置时具有价值。 利用 IronPDF 的强大功能进行稳健的 PDF 生成,并在类初始化优雅至关重要时运用 C# 主构造函数。 这种动态组合让您能够在 C# 编程的充满活力的世界中,以创造力和效率应对文档生成的复杂性。 IronPDF offers a free trial and its lite license starts from $799. 常见问题解答 主构造函数如何使 C# 代码更加简洁? 主构造函数允许您在类声明中直接声明和初始化属性,减少样板代码的数量并增强可读性。 C# 12 引入了哪些新功能? C# 12 引入了主构造函数、拦截器和集合表达式,为开发人员提供了更简洁和强大的语法选项。 主构造函数可以用于不可变数据结构吗? 是的,主构造函数非常适合用于不可变数据结构,因为它们允许直接在构造函数中初始化只读属性。 如何使用 C# 将 HTML 内容转换为 PDF? 您可以使用 IronPDF 的 ChromePdfRenderer 类将 HTML 内容转换为 PDF,确保输出文档中保留格式和样式。 使用 IronPDF 进行 PDF 生成的优势是什么? IronPDF 提供了一个强大的平台,用于在 C# 中创建和操作 PDF 文件,支持诸如 HTML 到 PDF 转换、PDF 合并以及详细的样式保留等功能。 主构造函数如何增强依赖注入? 主构造函数通过在构造函数参数中清晰地表明类依赖项,从而简化了依赖图的设置和维护。 主构造函数如何与 PDF 文档生成集成? 在使用诸如 IronPDF 之类的库时,主构造函数可用于初始化与 PDF 设置相关的配置类或结构,简化设置过程。 主构造函数的一些实际使用示例是什么? 实际示例包括几何形状层次结构的初始化和需要明晰性和简洁性的依赖注入场景。 开发人员如何开始在他们的项目中使用 IronPDF? 开发人员可以通过包管理器控制台或 NuGet 包管理器安装 IronPDF NuGet 包,并参考全面的文档以获取实现细节。 IronPDF 在文档生成流程中扮演什么角色? IronPDF 通过允许开发人员在 C# 中轻松创建、转换和操作 PDF,支持与其他 C# 功能的无缝集成,从而增强了文档生成流程。 Curtis Chau 立即与工程团队聊天 技术作家 Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。 相关文章 已更新九月 4, 2025 RandomNumberGenerator C# 使用 RandomNumberGenerator C# 类可以帮助将您的 PDF 生成和编辑项目提升到一个新的高度。 阅读更多 已更新九月 4, 2025 C# String Equals(开发者用法) 与强大的 PDF 库 IronPDF 结合使用,切换模式匹配允许您为文档处理构建更智能、更简洁的逻辑。 阅读更多 已更新八月 5, 2025 C# Switch 模式匹配(开发者用法) 与强大的 PDF 库 IronPDF 结合使用,切换模式匹配允许您为文档处理构建更智能、更简洁的逻辑。 阅读更多 空合并运算符 C#(开发者如何使用)C# 双问号(开发者如何使用)
已更新九月 4, 2025 RandomNumberGenerator C# 使用 RandomNumberGenerator C# 类可以帮助将您的 PDF 生成和编辑项目提升到一个新的高度。 阅读更多