.NET 帮助 C# 密封类(开发人员如何使用) Curtis Chau 已更新:六月 22, 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#语言为开发人员提供了一套多功能的工具,用于设计和实现稳健的软件。 其中一个为类继承增添额外控制层的功能是密封类的概念。 密封类提供了一种独特的方式来限制继承层次结构,提供一定程度的安全性和封装性,在某些情况下是有益的。 In this article, we will delve into the intricacies of the C# sealed classes and also explore the IronPDF NuGet package from Iron Software. 什么是密封类和密封方法? 密封类:在C#中,密封类是不能被继承的类。 通过使用sealed关键字,开发人员可以防止其他类从密封类派生或扩展。 这种有意识的限制确保了密封类不能被用作任何其他类的基类,从而限制了继承层次结构的范围。 密封类通常用于开发人员希望控制并最终确定类的结构,防止通过继承进行意外修改的情况。 在此示例中,IronPDF用于将HTML内容渲染为PDF文档,然后保存到指定位置。 public sealed class Animal { public string Species { get; set; } public void MakeSound() { Console.WriteLine("Generic animal sound"); } } // The following code will cause a compilation error because 'Animal' is sealed and cannot be inherited: // public class Dog : Animal // Error: Cannot inherit from sealed class 'Animal' // { // } public sealed class Animal { public string Species { get; set; } public void MakeSound() { Console.WriteLine("Generic animal sound"); } } // The following code will cause a compilation error because 'Animal' is sealed and cannot be inherited: // public class Dog : Animal // Error: Cannot inherit from sealed class 'Animal' // { // } Public NotInheritable Class Animal Public Property Species() As String Public Sub MakeSound() Console.WriteLine("Generic animal sound") End Sub End Class ' The following code will cause a compilation error because 'Animal' is sealed and cannot be inherited: ' public class Dog : Animal // Error: Cannot inherit from sealed class 'Animal' ' { ' } $vbLabelText $csharpLabel 与结构体不同,结构体是隐式密封的,密封类必须如上所示使用sealed关键字声明。 在这个例子中,Animal类被声明为密封类,使得任何其他类都不可能继承它。 密封方法:除了封装整个类之外,C#还允许开发人员在类中封装单个方法。 密封方法是派生类不能重写的方法。这确保了该方法的行为在所有子类中保持一致,为应用程序的逻辑提供了一定的可预测性。 要封装一个方法,使用sealed修饰符: public class Animal { public string Species { get; set; } // A virtual method allows derived classes to override it. public virtual void MakeSound() { Console.WriteLine("Generic animal sound"); } } public class Dog : Animal { // The sealed override prevents further overriding of this method. public sealed override void MakeSound() { Console.WriteLine("Bark!"); } } public class Animal { public string Species { get; set; } // A virtual method allows derived classes to override it. public virtual void MakeSound() { Console.WriteLine("Generic animal sound"); } } public class Dog : Animal { // The sealed override prevents further overriding of this method. public sealed override void MakeSound() { Console.WriteLine("Bark!"); } } Public Class Animal Public Property Species() As String ' A virtual method allows derived classes to override it. Public Overridable Sub MakeSound() Console.WriteLine("Generic animal sound") End Sub End Class Public Class Dog Inherits Animal ' The sealed override prevents further overriding of this method. Public NotOverridable Overrides Sub MakeSound() Console.WriteLine("Bark!") End Sub End Class $vbLabelText $csharpLabel virtual关键字允许在派生类中重写方法,而sealed关键字阻止在任何后续子类中进一步重写基类虚方法。 密封类和类成员:密封类还可以包括密封成员,例如属性、方法和事件。 这种密封类和密封成员的组合确保了对类行为和结构的高度控制。 在此示例中,IronPDF用于将HTML内容渲染为PDF文档,然后保存到指定位置。 public sealed class ControlledClass { // A sealed property that prevents overriding. public sealed string ControlledProperty { get; set; } // A method that cannot be redefined by derived classes. public virtual sealed void ControlledMethod() { // Method implementation Console.WriteLine("Executing controlled method."); } // A sealed event that cannot be subscribed to or raised by derived classes. public sealed event EventHandler ControlledEvent; // Sealed indexers, if applicable public sealed string this[int index] { get { return "Value"; } set { // Setter implementation } } } public sealed class ControlledClass { // A sealed property that prevents overriding. public sealed string ControlledProperty { get; set; } // A method that cannot be redefined by derived classes. public virtual sealed void ControlledMethod() { // Method implementation Console.WriteLine("Executing controlled method."); } // A sealed event that cannot be subscribed to or raised by derived classes. public sealed event EventHandler ControlledEvent; // Sealed indexers, if applicable public sealed string this[int index] { get { return "Value"; } set { // Setter implementation } } } Public NotInheritable Class ControlledClass ' A sealed property that prevents overriding. Public NotOverridable Property ControlledProperty() As String ' A method that cannot be redefined by derived classes. Public Overridable NotOverridable Sub ControlledMethod() ' Method implementation Console.WriteLine("Executing controlled method.") End Sub ' A sealed event that cannot be subscribed to or raised by derived classes. Public Event ControlledEvent As EventHandler ' Sealed indexers, if applicable Default Public NotOverridable Property Item(ByVal index As Integer) As String Get Return "Value" End Get Set(ByVal value As String) ' Setter implementation End Set End Property End Class $vbLabelText $csharpLabel 在此示例中,ControlledClass的每一个方面都是密封的-属性、方法、事件,甚至索引器(如果适用)。 这种密封程度提供了一个稳健且不可更改的结构,适用于需要保持类设计固定的场景。 密封类的理由 代码安全性:密封类通过防止未经授权的访问和修改有助于代码安全性。 当一个类被密封时,它作为一个闭合实体,具有明确定义的接口和行为。 这种封装极大程度地降低了意外副作用或改动的风险,这可能会影响代码库的稳定性和安全性。 设计完整性:在较大的代码库或框架中,维护设计完整性至关重要。 密封类作为具有固定结构的基础构件,减少意外修改的可能性。 这在某个类作为系统的核心组件,而它的行为应在不同模块之间保持一致的情况下特别有利。 使用密封类的最佳实践 谨慎使用密封类:尽管密封类提供了好处,但应该谨慎使用。 过度使用密封类可能导致代码刚性并不易维护。 记录意图:在封装类或方法时,记录此决定背后的意图至关重要。 解释为何特定类被密封以及导致该选择的设计考虑。 考虑未来的扩展性:在封装一个类之前,考虑未来的需求是否可能需要可扩展性。 如果一个类可能需要扩展,密封它可能会阻碍未来的开发。 使用密封方法以保持稳定性:当一个方法的核心行为应该在不同的子类中保持稳定时,密封方法是有益的。 这可以提高代码的可预测性。 不能同时是抽象的:密封类/密封方法不能同时是抽象类/抽象方法,因为抽象类被设计为让其他类继承,而密封类限制继承。 IronPDF 简介 IronPDF is a C# PDF library from IronPDF是Iron Software的C# PDF库,是一个现代的PDF生成器和阅读器。 安装 可以使用NuGet程序包管理器控制台或使用Visual Studio程序包管理器安装IronPDF。 以下是控制台的命令: Install-Package IronPdf 或者,要使用NuGet程序包管理器安装IronPDF,请在NuGet程序包管理器的搜索栏中搜索“ironpdf”。 IronPDF和密封类 一起使用密封关键字和IronPDF可以用于防止子类库或派生库重写继承的成员,并生成PDF。 namespace OrderBy { public class Program { static void Main() { Console.WriteLine("Demo Sealed Class and IronPdf"); var dog = new Dog(); dog.MakeSound(); dog.Print(); } } // Base class public class Animal { public string Species { get; set; } public virtual void MakeSound() { Console.WriteLine("Generic animal sound"); } public virtual void Print() { Console.WriteLine("Generic animal Print"); } } public class Dog : Animal { // Sealed override ensures method cannot be overridden in further derived classes. public sealed override void MakeSound() { Console.WriteLine("Bark!"); } public sealed override void Print() { var pdfRenderer = new ChromePdfRenderer(); string content = @" <!DOCTYPE html> <html> <body> <h1>Hello, Dog!</h1> <p>This is Print from Derived class.</p> <p>Print Animal Dog</p> <p>Print Animal Sound: Bark</p> </body> </html>"; pdfRenderer.RenderHtmlAsPdf(content).SaveAs("dog.pdf"); } } } namespace OrderBy { public class Program { static void Main() { Console.WriteLine("Demo Sealed Class and IronPdf"); var dog = new Dog(); dog.MakeSound(); dog.Print(); } } // Base class public class Animal { public string Species { get; set; } public virtual void MakeSound() { Console.WriteLine("Generic animal sound"); } public virtual void Print() { Console.WriteLine("Generic animal Print"); } } public class Dog : Animal { // Sealed override ensures method cannot be overridden in further derived classes. public sealed override void MakeSound() { Console.WriteLine("Bark!"); } public sealed override void Print() { var pdfRenderer = new ChromePdfRenderer(); string content = @" <!DOCTYPE html> <html> <body> <h1>Hello, Dog!</h1> <p>This is Print from Derived class.</p> <p>Print Animal Dog</p> <p>Print Animal Sound: Bark</p> </body> </html>"; pdfRenderer.RenderHtmlAsPdf(content).SaveAs("dog.pdf"); } } } Namespace OrderBy Public Class Program Shared Sub Main() Console.WriteLine("Demo Sealed Class and IronPdf") Dim dog As New Dog() dog.MakeSound() dog.Print() End Sub End Class ' Base class Public Class Animal Public Property Species() As String Public Overridable Sub MakeSound() Console.WriteLine("Generic animal sound") End Sub Public Overridable Sub Print() Console.WriteLine("Generic animal Print") End Sub End Class Public Class Dog Inherits Animal ' Sealed override ensures method cannot be overridden in further derived classes. Public NotOverridable Overrides Sub MakeSound() Console.WriteLine("Bark!") End Sub Public NotOverridable Overrides Sub Print() Dim pdfRenderer = New ChromePdfRenderer() Dim content As String = " <!DOCTYPE html> <html> <body> <h1>Hello, Dog!</h1> <p>This is Print from Derived class.</p> <p>Print Animal Dog</p> <p>Print Animal Sound: Bark</p> </body> </html>" pdfRenderer.RenderHtmlAsPdf(content).SaveAs("dog.pdf") End Sub End Class End Namespace $vbLabelText $csharpLabel 以下是从IronPDF生成的PDF 许可(提供免费试用) IronPDF。 该密钥需要放在appsettings.json中。 { "IronPdf.LicenseKey": "your license key" } 提供您的电子邮件以获取试用许可证。 结论 C# 密封类为开发人员提供了一种强大的机制来控制继承层次结构,并确保某些类及其成员不能被扩展或重写。 尽管需要谨慎考虑密封类的使用,但它们提供了一种有效的方式来封装功能并防止意外的修改。 通过理解密封类和方法的概念,开发人员可以做出关于何时何地应用这一限制的明智决定,从而有助于创建可维护、安全和可预测的软件系统。 再加上IronPDF,我们也可以打印PDF文档。 常见问题解答 C# 中的密封类如何工作? 在 C# 中,使用 sealed 关键字定义密封类。这防止其他类从其继承,确保类的实现保持不变。 为什么开发人员应该在 C# 中使用密封类? 密封类用于通过防止继承来维护代码的完整性。这确保了类的行为在较大系统中保持一致和安全,在这些系统中设计的完整性至关重要。 密封类可以有也被密封的方法吗? 是的,密封类可以包含自身被密封的方法。这意味着这些方法无法在派生类中被重写,进一步提高了类功能的安全性和一致性。 在类中使用密封方法有什么好处? 密封方法防止派生类重写,这有助于维护方法的原始行为,确保一致性并防止意外修改。 您能否提供使用密封类的例子? 当您希望锁定类的实现以防止通过继承进行更改时,例如在实用程序类中或处理需要稳定的敏感操作时,密封类非常有用。 密封类如何与 C# 中的 PDF 生成相关联? 使用 IronPDF 等 PDF 库时,可以利用密封类确保 PDF 生成过程保持一致和安全,通过防止通过继承进行修改。 是否可以将密封类与 IronPDF 等第三方库一起使用? 是的,密封类可以与 IronPDF 等第三方库一起使用,将 PDF 生成逻辑封装在一个安全、不可继承的类结构中。 如何使用 NuGet 安装 C# PDF 库? 您可以通过使用命令 dotnet add package IronPdf 或在 Visual Studio NuGet 包管理器中搜索 'ironpdf' 来安装 C# PDF 库,如 IronPDF。 在软件设计中使用密封类时需要考虑哪些因素? 开发人员应考虑未来的可扩展性需求,并记录密封类的原因。使用密封类可以提高安全性和可维护性,但应与应用程序所需的灵活性相平衡。 C# 开发人员推荐的 PDF 生成器是什么? IronPDF 是 C# 开发人员推荐的 PDF 生成器,作为 NuGet 包提供强大的 PDF 创建和操作能力。 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# LINQ Join 查询语法(开发...
已更新九月 4, 2025 RandomNumberGenerator C# 使用 RandomNumberGenerator C# 类可以帮助将您的 PDF 生成和编辑项目提升到一个新的高度。 阅读更多