如何在foreach循环中比较KeyValuePair.Value与指定值currentGold?
解决思路:给每个物品绑定可购买判断提示
你的问题出在当前的if语句输出的是通用提示,而且没有和具体物品关联,导致看起来所有物品都触发了提示。只要把提示内容和当前遍历到的物品绑定,就能明确区分每个物品的可购买状态。
修正后的代码
int currentGold = 100; Dictionary<string, int> itemInventory = new Dictionary<string, int>() { {"Armor", 18}, {"Weapon", 19}, {"Magic Skill", 22} }; Debug.LogFormat("Your inventory has: {0} items", itemInventory.Count); foreach (KeyValuePair<string, int> kvp in itemInventory) { // 先输出物品基础信息 Debug.LogFormat("Item: {0} - {1}g", kvp.Key, kvp.Value); // 针对当前物品判断购买力,输出对应提示 if (kvp.Value <= currentGold) // 若要刚好够钱也能买就用<=,只想钱比价格多就用< { Debug.LogFormat("You can afford the {0}", kvp.Key); } else { Debug.LogFormat("You can't afford the {0}", kvp.Key); } }
关键调整点
- 把提示内容里加上
kvp.Key,让提示明确指向当前物品,不再是无差别通用提示 - 增加
else分支,清晰显示买不起的物品状态,避免只有单一提示造成混淆 - 调整代码顺序,先输出物品信息再跟进状态提示,逻辑更连贯
如果不需要显示买不起的提示,只保留可购买的提示,简化版代码如下:
foreach (KeyValuePair<string, int> kvp in itemInventory) { Debug.LogFormat("Item: {0} - {1}g", kvp.Key, kvp.Value); if (kvp.Value < currentGold) { Debug.LogFormat("You can afford the {0}", kvp.Key); } }
这样每个提示都对应具体的可购买物品,不会再出现所有物品都触发相同提示的问题。
内容的提问来源于stack exchange,提问作者SadMan
相关产品推荐
相关产品推荐

