当前位置:首页 > 技术 > 正文内容

C# 面向对象设计:基于控制台的游戏资料管理系统

访客 技术 2026年7月20日 1

系统概述

本案例旨在演示如何利用 C# 的面向对象特性构建一个轻量级的终端应用程序。核心目标是通过类与对象的封装,实现对特定数字产品信息的增删改查(CRUD)操作。该系统采用控制台交互模式,通过定义枚举类型规范年龄分级,利用集合结构存储数据,并分离业务逻辑与入口流程。

数据模型设计

首先定义基础数据类型。为了规范年龄分级字段,避免使用杂乱的整数或字符串,这里引入枚举类型来限定可选值。

namespace ConsoleApp.Core
{
    // 定义产品适用年龄分级
    public enum RatingLevel
    {
        Under12 = 12,
        Under15 = 15,
        Under18 = 18
    }
}

接下来构建具体的产品实体类。建议使用属性(Property)而非公共字段来实现数据的简单封装,确保访问控制的安全性。

namespace ConsoleApp.Model
{
    /// <summary>
    /// 数字产品信息模型
    /// </summary>
    public class SoftwareItem
    {
        public int Id { get; set; }           // 唯一标识符
        public string SerialNumber { get; set; } // 序列号/公式
        public decimal Cost { get; set; }     // 单价
        public RatingLevel Level { get; set; } // 年龄评级
        public string Category { get; set; }  // 题材类型
    }
}

业务逻辑层

创建一个管理类来维护数据集合并提供操作方法。此处采用 List<T> 替代固定数组,以便更灵活地管理动态数据。主要包含初始化录入、信息更新、条件检索和全量展示四个功能模块。

using System;
using System.Collections.Generic;
using System.Linq;
using ConsoleApp.Model;

namespace ConsoleApp.Logic
{
    public class ItemManager
    {
        private readonly List<SoftwareItem> _items = new List<SoftwareItem>();

        // 批量录入功能
        public void RegisterBatch()
        {
            Console.WriteLine("=== 批量录入模式 ===");
            int count;
            if (int.TryParse(Console.ReadLine(), out count))
            {
                for (int i = 0; i < count; i++)
                {
                    var newItem = CreateNewItem(i + 1);
                    _items.Add(newItem);
                }
            }
        }

        // 辅助创建方法
        private SoftwareItem CreateNewItem(int id)
        {
            Console.Write($"[{id}] 输入序列号: ");
            string serial = Console.ReadLine();
            Console.Write($"[{id}] 输入价格: ");
            decimal cost = decimal.Parse(Console.ReadLine());
            Console.Write($"[{id}] 输入题材: ");
            string category = Console.ReadLine();
            Console.Write($"[{id}] 输入评级 (12|15|18): ");
            string ratingInput = Console.ReadLine();

            return new SoftwareItem
            {
                Id = id,
                SerialNumber = serial,
                Cost = cost,
                Category = category,
                Level = ParseRating(ratingInput)
            };
        }

        // 辅助解析枚举
        private static RatingLevel ParseRating(string input)
        {
            return (RatingLevel)Enum.Parse(typeof(RatingLevel), input);
        }

        // 修改指定记录
        public void UpdateDetails()
        {
            PrintTable();
            Console.WriteLine("请输入要修改的项目 ID:");
            int targetId = int.Parse(Console.ReadLine());
            var item = _items.FirstOrDefault(x => x.Id == targetId);

            if (item != null)
            {
                Console.Write("更新序列号 (回车跳过): ");
                string newSerial = Console.ReadLine();
                if (!string.IsNullOrEmpty(newSerial)) item.SerialNumber = newSerial;

                Console.Write("更新价格 (回车跳过): ");
                string priceStr = Console.ReadLine();
                if (!string.IsNullOrEmpty(priceStr)) item.Cost = decimal.Parse(priceStr);

                Console.Write("更新评级 (12|15|18): ");
                string rateStr = Console.ReadLine();
                if (!string.IsNullOrEmpty(rateStr)) item.Level = ParseRating(rateStr);
            }
        }

        // 条件筛选查询
        public void SearchInventory()
        {
            Console.WriteLine("输入查询序列号:");
            string key = Console.ReadLine();
            Console.WriteLine("输入查询评级:");
            RatingLevel keyRate = ParseRating(Console.ReadLine());

            Console.WriteLine("ID\t编号\t价格\t分级\t类型");
            foreach (var item in _items.Where(x => x.SerialNumber == key && x.Level == keyRate))
            {
                Console.WriteLine($"{item.Id}\t{x.SerialNumber}\t{x.Cost}\t{x.Level}\t{x.Category}");
            }
        }

        // 列表展示
        public void PrintTable()
        {
            Console.WriteLine("ID\t编号\t价格\t分级\t类型");
            foreach (var item in _items)
            {
                Console.WriteLine($"{item.Id}\t{x.SerialNumber}\t{x.Cost}\t{x.Level}\t{x.Category}");
            }
        }
    }
}

程序入口与流程控制

主入口负责实例化管理器对象,并通过死循环维持菜单运行状态。使用 if-else 结构判断用户指令,分别调用相应的业务方法。

using System;
using ConsoleApp.Logic;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var manager = new ItemManager();
            bool exit = false;

            while (!exit)
            {
                Console.Clear();
                Console.WriteLine("---------------- 主控菜单 ----------------");
                Console.WriteLine("1. 新增录入");
                Console.WriteLine("2. 修正信息");
                Console.WriteLine("3. 检索数据");
                Console.WriteLine("4. 查看全部");
                Console.WriteLine("5. 结束程序");
                Console.WriteLine("------------------------------------------");
                
                string choice = Console.ReadLine();

                switch (choice)
                {
                    case "1":
                        manager.RegisterBatch();
                        break;
                    case "2":
                        manager.UpdateDetails();
                        break;
                    case "3":
                        manager.SearchInventory();
                        break;
                    case "4":
                        manager.PrintTable();
                        break;
                    case "5":
                        exit = true;
                        break;
                    default:
                        Console.WriteLine("无效指令,请重试");
                        break;
                }
                
                if (!exit) Console.ReadKey();
            }
        }
    }
}

通过上述代码重构,我们将原本松散的逻辑整合到了标准的分层架构中。利用属性代替公开字段增强了安全性,使用泛型集合优化了内存管理,并通过枚举类型消除了魔法数字,整体提高了代码的可维护性与规范性。

相关文章

Linux crontab 详解

1) crontab 是什么cron 是 Linux 的定时任务守护进程;crontab 是用来编辑/查看“按时间周期执行命令”的表(cron table)。常见两类:用户 crontab:每个用户一份(crontab -e 编辑)系统级 crontab / cron.d:可指定执行用户(/etc/crontab、/etc/cron.d/*)2) crontab 时间...

富文本里可以允许的 HTML 属性

一、所有标签默认允许的安全属性(极少)class        (可选)id           (通常建议禁用)title️ 注意:id 容易被滥用做锚点注入,很多系统直接禁用class 允许的话最好只允许固定前缀(如 editor-*)二、a 标签允许属性<a href="" t...

Mac 安装 Node.js 指南

方法一:通过官网安装包(最简单,适合初学者)如果你只是想快速安装并开始使用,这是最直接的方法。访问 Node.js 官网。页面会显示两个版本:LTS (Recommended For Most Users):长期支持版,最稳定。建议选这个。Current:最新特性版,包含最新功能但可能不够稳定。下载 .pkg 安装包并运行。按照安装向导点击“下一步”即可完成。方法二:使用 Homebrew 安装(...

Dom\HTML_NO_DEFAULT_NS 的副作用:自动加闭合标签

在使用Dom\HTMLDocument时,Dom\HTML_NO_DEFAULT_NS 将禁止在解析过程中设置元素的命名空间, 此设置是为了与DOMDocument向后兼容而存在的。当使用它时,已知的一个副作用就是:自动加闭合标签例如 </img> 为什么会这样?当你使用:Dom\HTML_NO_DEFAULT_NS文档会变成 无命名空间模式,此时内部更接近 XML...

Laravel 事件和监听器创建

在 Laravel 中,使用 Artisan 命令创建 Events(事件) 和 Listeners(监听器) 是非常高效的。你可以通过以下几种方式来实现:1. 手动创建单个 Event如果你只想创建一个事件类,可以使用 make:event 命令:Bashphp artisan make:event UserRegistered执行后,文件将生成在 app/Even...

自定义域名解析神器 dnsmasq

什么是 dnsmasq?dnsmasq 是一个轻量级、功能强大的网络服务工具,专为小型和中等规模网络设计。它是一个综合的网络基础设施解决方案[1]。dnsmasq 能做什么?功能说明应用场景DNS 转发与缓存将 DNS 查询转发到上游服务器(ISP、Google DNS 等),并在本地缓存结果加快 DNS 查询速度,减少外部 DNS 流量本地 DNS解析本地网络设备的主机名,无需编辑&n...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。