跳转至

综合练习:图书管理系统#

来源:D:\study\C#1\stu0725\6 题目:图书管理系统的核心架构

这个练习综合运用了继承、readonlyconstbase 调用等知识点,模拟图书馆的图书管理场景。

类设计#

Book(基类)
  ├─ readonly Isbn    — 图书 ISBN 号
  ├─ const LibraryName — 图书馆名称
  └─ Title / Author / Price

AudioBook(继承 Book)
  └─ Duration — 有声书时长(分钟)

Player(基类)
  ├─ Name — 玩家姓名
  └─ Handcards — 手牌

Farmer(继承 Player)— 农民角色
Landlord(继承 Player)— 地主角色

核心代码#

// ── Book 与 AudioBook ──
class Book
{
    public readonly int Isbn;
    public const string LibraryName = "市立图书馆";
    public string Title { get; set; }
    public string Author { get; set; }
    public decimal Price { get; set; }

    public Book(int isbn, string title, string author, decimal price)
    {
        Isbn = isbn;
        Title = title;
        Price = price;
    }

    public void ShowInfo()
    {
        Console.WriteLine(
            $"====图书详情====\n图书馆:{LibraryName}\n书名:{Title}\n作者:{Author}\n价格:{Price}");
    }
}

class AudioBook : Book
{
    public int Duration { get; set; }

    // base() 传递父类参数
    public AudioBook(int isbn, string title, string author, decimal price, int duration)
        : base(isbn, title, author, price)
    {
        Duration = duration;
    }

    // 重写 ShowInfo — 先调用父类方法,再补充子类信息
    public new void ShowInfo()
    {
        base.ShowInfo();
        Console.WriteLine($"有声书:时长{Duration}分钟");
    }
}

// ── Player、Farmer、Landlord ──
class Player
{
    public string Name { get; set; }
    public string[] Handcards { get; set; }

    public Player(string name, string[] handcards)
    {
        Name = name;
        Handcards = handcards;
    }
}

class Farmer : Player
{
    public string Id { get; set; }

    public Farmer(string name, string[] handcards, string id) : base(name, handcards)
    {
        Id = id;
    }
}

class Landlord : Player
{
    public string Id { get; set; }

    public Landlord(string name, string[] handcards, string id) : base(name, handcards)
    {
        Id = id;
    }
}

使用示例#

Book book = new Book(9053, "活着", "余华", 12.5m);
AudioBook audioBook = new AudioBook(8964, "活着", "余华", 12.5m, 100);

book.ShowInfo();
// ====图书详情====
// 图书馆:市立图书馆
// 书名:活着
// 作者:余华
// 价格:12.5

audioBook.ShowInfo();
// ====图书详情====       ← base.ShowInfo() 的输出
// 图书馆:市立图书馆
// 书名:活着
// 作者:余华
// 价格:12.5
// 有声书:时长100分钟    ← 子类补充的信息

知识点总结#

知识点 应用位置
readonly Book.Isbn — 每本书的 ISBN 在构造时确定,之后不可改
const Book.LibraryName — 图书馆名称全局统一,编译时常量
继承 AudioBook : BookFarmer : PlayerLandlord : Player
base() AudioBook 构造函数调用 base(isbn, ...) 初始化父类
new 关键字 AudioBook.ShowInfo()new 隐藏父类同名方法(而非 override)


相关笔记#