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

如何用自定义变量参数向列表添加元素?C#控制台RPG库存为空排查

问题分析与修复方案

核心问题

你在BasicStatus()和ShowInventory()里分别创建了完全独立的Inventory实例:

  • BasicStatus()里的inventory是方法内部的局部变量,添加完物品后,这个实例会在方法执行结束后被销毁,物品数据根本没保留下来
  • ShowInventory()里又新建了一个空的Inventory,它和之前那个实例没有任何关联,自然打印不出物品

修复方案(两种可选)

方案1:用静态字段共享Inventory实例

在Program类里定义一个静态的Inventory对象,让两个方法共用同一个实例:

internal class Program
{
    // 静态字段,全局共享同一个背包实例
    static Inventory _playerInventory = new Inventory();

    static void Main(string[] args)
    {
        BasicStatus();
        ShowInventory();
    }

    static void BasicStatus()
    {
        Item weap1 = new Item("Old Sword", "ATK", 2, "Common");
        Item armo1 = new Item("Iron Armor", "DEF", 5, "Uncommon");

        // 往共享的背包里加物品
        _playerInventory.GetItem(weap1);
        _playerInventory.GetItem(armo1);
    }

    static void ShowInventory()
    {
        Console.Clear();
        Console.WriteLine("[ITEM LIST]");

        // 遍历共享背包的物品
        foreach (var item in _playerInventory.items)
        {
            Console.WriteLine($"- {item.Name} | {item.Type} +{item.Effect} | {item.Info}");
        }
    }
}

方案2:通过参数传递Inventory实例

在Main方法里创建Inventory,再把它传给两个方法,保证用的是同一个对象:

internal class Program
{
    static void Main(string[] args)
    {
        Inventory playerInventory = new Inventory();
        BasicStatus(playerInventory);
        ShowInventory(playerInventory);
    }

    // 修改方法,接收外部传入的背包
    static void BasicStatus(Inventory inventory)
    {
        Item weap1 = new Item("Old Sword", "ATK", 2, "Common");
        Item armo1 = new Item("Iron Armor", "DEF", 5, "Uncommon");

        inventory.GetItem(weap1);
        inventory.GetItem(armo1);
    }

    // 修改方法,接收外部传入的背包
    static void ShowInventory(Inventory inventory)
    {
        Console.Clear();
        Console.WriteLine("[ITEM LIST]");

        foreach (var item in inventory.items)
        {
            Console.WriteLine($"- {item.Name} | {item.Type} +{item.Effect} | {item.Info}");
        }
    }
}

补充说明

  • 静态字段方案适合小型Demo,简单直接
  • 参数传递方案更符合面向对象设计原则,扩展性更强,后续如果要做多角色背包会更方便

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 20:12:35