C# 密封类和密封方法

来源:互联网 发布:灵界基友网络剧下载 编辑:程序博客网 时间:2024/04/25 07:18
在C#中,为了确保其他类不可以派生于某一类,可以使用sealed关键字密封该类,对某个类使用 sealed关键字作为前缀,这样可以防止其他类继承自该类,如public sealed class Square:Rectangle{}

下面的语句将导致产生错误:

///---Error:Square is sealed---

public class Rhombus:Square

{}

密封类中不能包含虚方法(Virtual)和抽象方法(abstract),因为在密封的类没有为派生类提供实现其虚方法和抽象方法的机会。

也可以使用密封方法,从而其他派生类不可以重写在当前类中提供的实现,如

public class Rectangle:Shape{     public override double Area()     {         return this.length*this.width;      }}
为了防止Rectangle的派生类(如Square)修改Area()实现,可使用sealed 关键字作为该方法的前缀,如:

public class Rectangle:Shape{     public override sealed double Area()     {         return this.length*this.width;      }}
现在,如果尝试重写Square类中的Area()方法,会产生错误:

public class Square:Rectangle{
     ///---Error:Area() is sealed in Rectangle class---        public override  double Area()     {        ///具体实现      }}



原创粉丝点击