【发布时间】:2023-04-01 12:07:01
【问题描述】:
类中的方法从用户那里接受一个整数以从列表中删除。该代码有效。我的问题是我不明白它为什么起作用;事实上,据我所知,它不应该工作。
public void Remove(int ValueToRemove)
{
bool isFound = false;
for (int count = 0; count < CurrentIndex; count++)
{
if (list[count] == ValueToRemove && !isFound)
{
isFound = true;
CurrentIndex = CurrentIndex -1;
}
if (isFound && ((count + 1) < list.Length))
{
list[count] = list[count + 1];
}
}
}
语句不应该...
if(list[count] == ValueToRemove && !isFound)
...总是评估为假,因此跳过运行大括号内的代码? !isFound 不等同于评估
if(list[count] == ValueToRemove && isFound == true)
在代码中...
if (list[count] == ValueToRemove && !isFound)
{
isFound = true;
CurrentIndex = CurrentIndex -1;
}
...如果 CurrentIndex = CurrentIndex - 1,使 CurrentIndex 比原来的值小一,那么前一个索引会发生什么情况?
最后...
if (isFound && ((count + 1) < list.Length))
{
list[count] = list[count + 1];
}
... list[count] 的值是否等于下一个索引的值(例如,索引 5 等于索引 6 中的任何值),或者该索引中包含的值是否等于更高的值(例如,如果索引 5 包含 10 的值,那么索引 5 现在将等于 11)
【问题讨论】:
-
不,因为
!isFound是isfound==false将!isFound读取为not isFound -
一篇文章中有多个问题并不理想。
-
阅读这里关于逻辑否定运算符 (!) msdn.microsoft.com/en-us/library/f2kd6eb2.aspx
-
值得注意的是,函数参数的标准大写约定是Camel Case——所以
ValueToRemove应该是valueToRemove -
如果
!isFound等同于isFound == true,您认为isFound等同于什么??