单继承,聚合和Sealed密封(C#)

C#是单继承语言

在需要多继承类结构时,一种解决方法是利用聚合:将希望的"基类"作为派生类的一个字段添加,然后将相关属性委

为聚合类的属性。


密封类,关键词是Sealed

字面意思就是将类密封起来,不让它派生出其他类,在需要把类设计为密封类的时候,将类标记为Sealed即可。


看下面例子:

public sealed partial class InheritanceExample2 : Page
{
    public InheritanceExample2()
    {
        this.InitializeComponent();

        Surface surface = new Surface();
        surface.HandWritingPen = "Surface Pen";
        surface.Brand = "Microsoft";
        surface.OperationSystem = "Windows 10";
        surface.Keyboard = "Type Cover";
        surface.HardDiskSize = "256GB";
        txtblk1.Text = string.Format("Surface平板电脑品牌:{0},自带{1}系统,手写笔叫{2}", surface.Brand, surface.OperationSystem
            , surface.HandWritingPen);
        txtblk2.Text = string.Format("Surface平板电脑:键盘是{0},硬盘有{1}", surface.Keyboard, surface.HardDiskSize);
    }

}
//传统PC
sealed class PC
{
    public string ScreenSize { get; set; }
}

//笔记本电脑(这边看作是聚合类,因为Surface已经从Tablet派生了,不能再继承Laptop)
class Laptop
{
    //静态属性
    public static string Keyboard { get; set; }

    public string HardDiskSize { get; set; }
}

//平板(Surface类继承自Tablet类)
class Tablet
{
    public string Brand { get; set; }

    public string OperationSystem { get; set; }
}

//微软的Surface系列平板电脑兼具笔记电脑的强大办公和平板方便便捷的优势,是两者结合的一种惊艳产物
//C#中只支持单继承,在某种情况下一个类需要从两个类派生却不能
//与之解决问题的办法就是使用聚合,让一个"基类"作为派生类的字段
class Surface:Tablet
{
    public string HandWritingPen { get; set; }

    private Laptop InternalLaptop { get; set; }//将Laptop类作为聚合类使用
    public string Keyboard
    {
        get { return Laptop.Keyboard; }
        set { Laptop.Keyboard = value; }
    }

    public string HardDiskSize
    {
        get { return InternalLaptop.HardDiskSize; }
        set { InternalLaptop.HardDiskSize = value; }
    }
    public Surface()
    {
        InternalLaptop = new Laptop();//在Surface类构造函数中将Laptop初始化很重要
    }
}

//华为发布的MateBook
//class MateBook:PC{} -- 错误:MateBook不能从密封类型PC派生

结果截图:

猜你喜欢

转载自blog.csdn.net/u010792238/article/details/50856798