所以我正在阅读这个问题return True stop the loop in Python?,但它在python和im in c#
无论如何我有一个看起来像这样的方法
public bool HasRequirements(string upgradeName){
for (int i = 0; i < upgradeRequirements [upgradeName].Length; i++) {
if (upgradesPurchased [upgradeRequirements [upgradeName] [i]]) {
return true;
} else {
return false;
}
}
return false;
}
编码时,我认为返回true会停止for块的执行,所以当你有一个for块执行时,我会想到如何为boolean
返回类型返回true?
答案 0 :(得分:1)
根据你的评论,另一个扩展函数只有在所有迭代都为真时才返回true:
public bool HasRequirements(string upgradeName){
for (int i = 0; i < upgradeRequirements [upgradeName].Length; i++) {
if (upgradesPurchased [upgradeRequirements [upgradeName] [i]]) {
// we skip return true
continue;
} else {
// false condition, immed return false
return false;
}
}
// we did not met false - so we can return true
return true;
}
如果您想获得多个结果&#39; - 另一种可能性是使用yield语句。您可以在此处找到详细描述它的帖子:What is the yield keyword used for in C#?
使用yield会继续根据以下枚举返回值。之后,如果一切都为真,则可以检查返回值:
public IEnumerable<bool> HasRequirements(string upgradeName)
{
bool returnValue = false;
for (int i = 0; i < upgradeRequirements[upgradeName].Length; i++)
{
if (upgradesPurchased[upgradeRequirements[upgradeName][i]])
{
yield return true;
}
else
{
yield return false;
}
}
yield return returnValue;
}
答案 1 :(得分:1)
&#34;如果一个组件尚未购买,那么它应该返回false,否则如果所有组件都被购买,则它应该返回true&#34;
也许你需要从你前进的地方开始思考:
public bool HasRequirements(string upgradeName)
{
for (int i = 0; i < upgradeRequirements [upgradeName].Length; i++)
{
if (upgradesPurchased [upgradeRequirements [upgradeName] [i]])
{
continue;
} else {
return false; // if one component has not been bought
}
}
return true; // all components were bought
}
现在,如果当前正在检查的购买已完成,那么继续下一步,基本上忽略它并继续前进。但如果没有完成,就足以认为当前状态有问题,所以返回错误并放弃再检查,因为它最终会是假的。