[英]I don't understand why this code works?
類中的方法接受用戶的整數以從列表中刪除。 該代碼有效。 我的問題是我不明白為什么會這樣。 事實上,據我所知,這不應該工作。
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等於當前值等於1,那么前一個索引會發生什么?
最后...
if (isFound && ((count + 1) < list.Length))
{
list[count] = list[count + 1];
}
...使list [count]的值等於下一個索引的值(例如,索引5等於索引6中的值),或者該索引中包含的值等於高一個(例如,如果索引5包含值10,則索引5現在等於11)
由於isFound
為false,因此!isFound
計算結果為true,並輸入了if語句。
這意味着!isFound
等同於說:
isFound == false
...如果CurrentIndex = CurrentIndex-1,則使CurrentIndex等於當前值等於1,那么前一個索引會發生什么?
上一個索引沒有任何反應,而是在列表中的當前項目上重復了該循環。
...使list [count]的值等於下一個索引的值(例如,索引5等於索引6中的值),或者該索引中包含的值等於高一個(例如,如果索引5包含值10,則索引5現在等於11)
它獲取列表中下一項的值,並將其分配給list[count]
。
您可以通過設置斷點並通過代碼進行調試,查看正在發生的情況並隨時檢查值來自己回答很多這類問題。
要回答有關此問題:
if (isFound && ((count + 1) < list.Length))
{
list[count] = list[count + 1];
}
該條件首先檢查下一個索引是否存在,然后將該下一個索引的值分配給當前值。 換句話說,如果count = 5,則它首先檢查以確保list [6]不會導致未定義的偏移量,然后list [5] = list [6]會將list [6]中的值分配給list [ 5]。 因此,如果list [5]為10,list [6]為11,則list [5]變為11。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.