You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#入门求助:如何为Character类添加物品库存并关联可用物品?

为C#角色类实现库存功能的解决方案

问题描述

我是C#编程新手,这是入门级问题但一直解决不了。已经写好MainProgram、Character和Item三个类,但没法整合实现需求:程序启动时创建Item实例列表availableItems,同时生成Character实例,想给这个角色添加能使用这些物品的库存,但尝试在Character构造函数中加空列表、通过公共方法创建currentInventory列表都出现编译错误,现在程序处于可运行状态,求指导如何实现角色的库存功能。

修改后的完整代码

using System;
using System.Collections.Generic;

namespace ClassMaster
{
    public class Item : IEquatable<Item>
    {
        public string Name { get; set; } = "";
        public int Id { get; set; }
        public int Effect { get; set; }

        public Item(int id, string name, int effect)
        {
            Id = id;
            Name = name;
            Effect = effect;
        }

        public void PrintItem()
        {
            Console.WriteLine("库存物品 ID: " + Id + " 名称: " + Name);
        }

        // 正确实现IEquatable<Item>的Equals方法,用于判断物品是否相同
        public bool Equals(Item? other)
        {
            if (other == null) return false;
            return Id == other.Id && Name == other.Name && Effect == other.Effect;
        }

        // 重写Object的Equals和GetHashCode,保持一致性
        public override bool Equals(object? obj)
        {
            return Equals(obj as Item);
        }

        public override int GetHashCode()
        {
            return HashCode.Combine(Id, Name, Effect);
        }
    }

    public class Character
    {
        // 私有字段存储角色名称,保持封装
        private string Name { get; set; }
        public int Age { get; set; }
        public int Health { get; set; } = 100;
        // 私有库存列表,对外通过方法操作,保证数据安全性
        private List<Item> _inventory = new List<Item>();

        public Character(string name, int age)
        {
            Name = name;
            Age = age;
        }

        public void PrintCharacter()
        {
            Console.WriteLine("名称: " + Name + " 年龄: " + Age + " 生命值: " + Health);
        }

        // 公共方法:添加物品到库存
        public void AddItemToInventory(Item item)
        {
            if (item != null && !_inventory.Contains(item))
            {
                _inventory.Add(item);
                Console.WriteLine($"已将{item.Name}添加到{Name}的库存");
            }
            else if (_inventory.Contains(item))
            {
                Console.WriteLine($"{Name}的库存中已有{item.Name}");
            }
        }

        // 公共方法:打印当前库存
        public void PrintInventory()
        {
            Console.WriteLine($"{Name}的库存:");
            if (_inventory.Count == 0)
            {
                Console.WriteLine("空");
                return;
            }
            foreach (var item in _inventory)
            {
                item.PrintItem();
            }
        }

        // 可选:使用物品的方法,示例为使用恢复类物品
        public void UseItem(Item item)
        {
            if (_inventory.Contains(item))
            {
                Health += item.Effect;
                // 限制生命值不超过初始值
                Health = Math.Min(Health, 100);
                _inventory.Remove(item);
                Console.WriteLine($"{Name}使用了{item.Name},生命值恢复至{Health}");
            }
            else
            {
                Console.WriteLine($"{Name}的库存中没有{item.Name}");
            }
        }
    }

    internal class MainProgram
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Console.WriteLine("");

            // 创建可用物品列表
            List<Item> availableItems = new List<Item>();

            // 添加物品
            availableItems.Add(new Item(1, "剑", 10));
            availableItems.Add(new Item(2, "凤凰尾羽", 10));
            availableItems.Add(new Item(3, "药水", 100));
            availableItems.Add(new Item(4, "奶酪", 50));
            
            Console.WriteLine("可用物品列表:");
            foreach (Item item in availableItems)
            {
                Console.WriteLine($"ID: {item.Id} 名称: {item.Name} 效果: {item.Effect}");
                Console.WriteLine();
            }

            Character tom = new Character("汤姆", 23);
            tom.PrintCharacter();

            // 演示添加物品到库存
            tom.AddItemToInventory(availableItems[2]);
            tom.AddItemToInventory(availableItems[0]);
            // 尝试重复添加
            tom.AddItemToInventory(availableItems[2]);

            // 打印库存
            tom.PrintInventory();

            // 演示使用物品
            tom.UseItem(availableItems[2]);
            tom.PrintInventory();
            tom.PrintCharacter();

            Console.ReadLine(); 
        }
    }
}

关键修改说明

  • Character类添加库存:在Character类中声明私有List<Item> _inventory字段,并在类初始化时直接创建空列表(避免构造函数中出错),通过公共方法AddItemToInventory、PrintInventory、UseItem来操作和访问库存,保证封装性。
  • 修复Item类的Equals方法:因为实现了IEquatable<Item>接口,必须正确实现Equals逻辑,否则Contains等列表方法无法正确判断物品是否存在,同时重写了object类的Equals和GetHashCode方法保持一致性。
  • Main方法中演示功能:添加了给角色添加物品、重复添加、打印库存、使用物品的示例代码,验证库存功能正常运行。

内容的提问来源于stack exchange,提问作者user17511401

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 03:42:15