簡體   English   中英

每次迭代都會評估 for 循環中的條件嗎?

[英]Is the condition in a for loop evaluated each iteration?

當您執行以下操作時:

for (int i = 0; i < collection.Count; ++i )

每次迭代都會調用collection.Count嗎?

如果 Count 屬性在調用時動態獲取計數,結果會改變嗎?

Yes Count 將在每一次通過時進行評估。 原因是在循環執行期間可能會修改集合。 給定循環結構,變量 i 應該表示迭代期間集合中的有效索引。 如果沒有在每個循環上都進行檢查,那么這不能證明是正確的。 示例案例

for ( int i = 0; i < collection.Count; i++ ) {
  collection.Clear();
}

此規則的一個例外是循環遍歷約束為長度的數組。

for ( int i = 0; i < someArray.Length; i++ ) {
  // Code
}

在某些情況下,CLR JIT 將特例這種類型的循環,因為數組的長度不能改變。 在這些情況下,邊界檢查只會發生一次。

參考: http://blogs.msdn.com/brada/archive/2005/04/23/411321.aspx

每次通過都會評估計數。 如果您繼續添加到集合中並且迭代器從未趕上,您將有一個無限循環。

class Program
    {
        static void Main(string[] args)
        {
            List<int> intCollection = new List<int>();
            for(int i=-1;i < intCollection.Count;i++)
            {
                intCollection.Add(i + 1);
            }
        }
    }

這最終將退出 memory 異常。

是的,從 i 初始化后的第一次迭代到檢查失敗並退出 for 循環的最后一次迭代,每次調用都會檢查計數。 如果需要,您可以修改 collections 計數,但要意識到您可能會陷入無限循環。

旁注,這不是為 VB 中的每個交互檢查。

與 C# 不同,VB 緩存了集合的結果.Count。

編輯:

C# for 循環的文字 VB 版本是:

Dim i = 0
Do While i < collection.Count
    'code goes here
    i+=1
Loop

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM