如何在if语句中检查字典中的多个值?



我刚刚开始学习unity,在我的一本c#学习书中看到了这个任务。我必须在foreach中使用if语句创建一个代码,以便它检查我是否可以负担字典中的每个项目,但我不知道如何检查所有项目,甚至一次特定的,所以我可以写3次,例如。

此刻我的日志显示了所有的项目和它们的值,但显示如果我只能买得起第一个。我应该把什么放在IF括号检查每一个值后,它出现它的日志?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LearningCurve : MonoBehaviour
{
public int currentGold = 3;
void Start()
{
Dictionary<string, int> itemInventory = new Dictionary<string, int>()
{
{"Potions", 4 },
{"Daggers", 3 },
{"Lockpicks", 1 }
};
foreach (KeyValuePair<string, int> itemCost in itemInventory)
{
Debug.LogFormat("Item {0} - {1}g", itemCost.Key, itemCost.Value);
if (currentGold >= itemCost.Value)
{
Debug.Log("I can afford that!");
}
}
}

我不确定我是否理解了这个问题,但我会尽量给你一个基本的概述,看看你发布的代码中发生了什么。让我们从if开始,if块的工作原理很简单,你在c#中放一个布尔bool,它可以有两个不同的值true和false,在if(bool VALUE)中,如果值为true,它将运行{code TO run}之间的代码。让我们稍微重构一下代码,看看这里发生了什么。

Dictionary<string, int> itemInventory = new Dictionary<string, int>()
{
{"Potions", 4 },
{"Daggers", 3 },
{"Lockpicks", 1 }
};
foreach (KeyValuePair<string, int> itemCost in itemInventory)
{

Debug.LogFormat("Item {0} - {1}g", itemCost.Key, itemCost.Value);
bool iCanBuyitem = currentGold >= itemCost.Value;
Debug.LogFormat("{0} >= {1} is {2}", currentGold, itemCost.Value,iCanBuyitem);
if (iCanBuyitem)
{
Debug.LogFormat("I can buy {0} ", itemCost.Key);
}else
{
Debug.LogFormat("I can't buy {0} ", itemCost.Key);
}
}

不像在数学中,在编程中symbol>=不是一个等式符号而是一个二进制运算符,它取c#中众多数值类型之一的两个变量在你的字典中它们是整数并生成一个bool值,该值告诉您一个数字是否大于或等于另一个数字,该方法具有类似于以下签名public bool FirstIsBiggerOrEqualToSecond(int first, int second)的内容下面是一个dotnet演示输出https://dotnetfiddle.net/oWlYlY

阅读问题头你的意思是,如果你想在if中放入两个或多个条件,你必须使用&&运算符:

if (currentGold >= itemCost.Value && currentGold <= 15)
{
Debug.Log("I have enough gold to buy this item and it's cheap.");
}

最新更新