首页 > 解决方案 > 布尔返回类型不应该总是返回真或假吗?

问题描述

这是一种根据列表计数返回 true 或 false 的方法。我一直认为 bool 返回类型需要返回trueor false。我不明白。如果这个问题太愚蠢,我很抱歉。

private static bool AdjustIndexForList<t>(IList<t> list, ref int index)
{
 if(index<0)
  index += list.count;
 else if (index >= list.count)
   index = list.count - 1;
//I do not understand this part. What is this returning?
return index >= 0;
}

这是对方法的调用

if(!adjustIndexForList(list, ref minIndex)
return false;

标签: c#.net

解决方案


>=被称为大于等于比较运算符,它检查左右操作数,true如果左侧计数大于或等于右侧计数,则返回false

在你的情况下,

return index >= 0;true如果 index 大于等于零,它将返回,否则 返回false


if(index >= 0)   //execute if block if index is greater than equal to zero
    return true;  // return true

如果条件是,上述一种衬里解决方案,

return index >= 0; //returns "true" if index is greater than equal to zero

推荐阅读