43.C# 类的继承

2024-03-13  本文已影响0人  技术老小子

摘要


继承是面向对象程序设计中最重要的概念之一。继承允许我们根据一个类来定义另一个类,这使得创建和维护应用程序变得更容易。同时也有利于重用代码和节省开发时间。

当创建一个类时,程序员不需要完全重新编写新的数据成员和成员函数,只需要设计一个新的类,继承了已有的类的成员即可。这个已有的类被称为的基类,这个新的类被称为派生类。

正文


C#只能继承来自一个类,接口允许多继承。

设备属于物料,工具与属于物料,这个基类就是物料类。

C# 中创建派生类的语法

创建类

public class Material
{
    public string Name { get; set; }
    public string Description { get; set; }
    public int Qty { get; set; }    
}

/// <summary>
/// 继承Material
/// </summary>
public class Equipment : Material
{
    //一个自己独有的品牌属性
    public string Brand { get;set; }

    public void Print()
    {
        Console.WriteLine($"名称{this.Name},描述{this.Description},数量{this.Qty},品牌{this.Brand}");
    }
}

/// <summary>
/// 继承Material
/// </summary>
public class Tool : Material
{
    //一个自己独有的使用者信息
    public string Owner { get;set; }

    public void Print()
    {
        Console.WriteLine($"名称{this.Name},使用者{this.Owner}");

    }
}

调用

Equipment equipment = new Equipment();
equipment.Name = "设备01";
equipment.Description = "生产用的";
equipment.Qty = 10;
equipment.Print();

Tool tool=new Tool();
tool.Name = "螺丝刀";
tool.Owner = "张三";
tool.Print();

protected 修饰

受保护成员在其所在的类中可由派生类实例访问

public class Material
{
    public string Name { get; set; }
    public string Description { get; set; }

    //修改为保护,这时项目直接调用会出错了
    protected int Qty { get; set; }    

    public void InStock(int qty)
    {
        this.Qty+=qty;
    }

    public void OutStock(int qty)
    {
        this.Qty -= qty;
    }
}

调用修改

Equipment equipment = new Equipment();
equipment.Name = "设备01";
equipment.Description = "生产用的";
//equipment.Qty = 10;//这样会出错了,因为是保护修饰
equipment.InStock(10);
equipment.Print();

Tool tool=new Tool();
tool.Name = "螺丝刀";
tool.Owner = "张三";
tool.Print();

上一篇 下一篇

猜你喜欢

热点阅读