
C# 密封类(开发人员如何使用)
在面向对象编程的世界中,C#语言为开发人员提供了一套多功能的工具,用于设计和实现稳健的软件。 其中一个为类继承增添额外控制层的功能是密封类的概念。 密封类提供了一种独特的方式来限制继承层次结构,提供一定程度的安全性和封装性,在某些情况下是有益的。 在本文中,我们将深入探讨 C# 密封类的复杂性,并探索来自 IronPDF 的 NuGet 包,来自 Iron Software。
什么是密封类和密封方法?
**密封类:**在C#中,密封类是不能被继承的类。 通过使用sealed关键字,开发者可以防止其他类从密封类派生或扩展。 这种有意识的限制确保了密封类不能被用作任何其他类的基类,从而限制了继承层次结构的范围。 密封类通常用于开发人员希望控制并最终确定类的结构,防止通过继承进行意外修改的情况。
请考虑以下示例:
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'
' {
' }与隐式密封的结构不同,密封类必须使用如上所示的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 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 Classsealed关键字则防止在任何后续子类中进一步重写基类虚方法。
**密封类和类成员:**密封类还可以包括密封成员,例如属性、方法和事件。 这种密封类和密封成员的组合确保了对类行为和结构的高度控制。
请考虑以下示例:
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在这个例子中,ControlledClass的每个方面都是密封的——属性、方法、事件,甚至是适用的索引器。 这种密封程度提供了一个稳健且不可更改的结构,适用于需要保持类设计固定的场景。
密封类的理由
**代码安全性:**密封类通过防止未经授权的访问和修改有助于代码安全性。 当一个类被密封时,它作为一个闭合实体,具有明确定义的接口和行为。 这种封装极大程度地降低了意外副作用或改动的风险,这可能会影响代码库的稳定性和安全性。
**设计完整性:**在较大的代码库或框架中,维护设计完整性至关重要。 密封类作为具有固定结构的基础构件,减少意外修改的可能性。 这在某个类作为系统的核心组件,而它的行为应在不同模块之间保持一致的情况下特别有利。
使用密封类的最佳实践
- **谨慎使用密封类:**尽管密封类提供了好处,但应该谨慎使用。 过度使用密封类可能导致代码刚性并不易维护。
- **记录意图:**在封装类或方法时,记录此决定背后的意图至关重要。 解释为何特定类被密封以及导致该选择的设计考虑。
- **考虑未来的扩展性:**在封装一个类之前,考虑未来的需求是否可能需要可扩展性。 如果一个类可能需要扩展,密封它可能会阻碍未来的开发。
- **使用密封方法以保持稳定性:**当一个方法的核心行为应该在不同的子类中保持稳定时,密封方法是有益的。 这可以提高代码的可预测性。
- **不能同时是抽象的:**密封类/密封方法不能同时是抽象类/抽象方法,因为抽象类被设计为让其他类继承,而密封类限制继承。
IronPDF 简介

IronPDF是Iron Software的C# PDF库,是一个现代的PDF生成器和阅读器。
安装
可以使用NuGet程序包管理器控制台或使用Visual Studio程序包管理器安装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
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 As 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
以下是从IronPDF生成的PDF

许可(提供免费试用)
IronPDF。 该密钥需要放在appsettings.json中。
{
"IronPdf.LicenseKey": "your license key"
}
提供您的电子邮件以获取试用许可证。
结论
C# 密封类为开发人员提供了一种强大的机制来控制继承层次结构,并确保某些类及其成员不能被扩展或重写。 尽管需要谨慎考虑密封类的使用,但它们提供了一种有效的方式来封装功能并防止意外的修改。 通过理解密封类和方法的概念,开发人员可以做出关于何时何地应用这一限制的明智决定,从而有助于创建可维护、安全和可预测的软件系统。 再加上IronPDF,我们也可以打印PDF文档。

Jacob Mellor 是 Iron Software 的首席技术官,也是一位开创 C# PDF 技术的有远见的工程师。作为 Iron Software 核心代码库的原始开发者,他从公司成立之初就开始塑造公司的产品架构,与首席执行官 Cameron Rimington 一起将公司转变为一家拥有 50 多名员工的公司,为 NASA、特斯拉和全球政府机构提供服务。
相关文章


