理解和解決” .NET”索引超出範圍錯誤
> 當您嘗試使用無效索引中訪問集合中的項目(例如數組或列表)中時,出現了.net中出現的“ indexoutofrangeException”。 因為.NET集合為零索引,因此有效的索引範圍為0到(長度-1)。 試圖訪問超出此範圍的元素(使用負數等於或大於長度的索引)觸發此例外。讓我們用一個數組示例說明:
<code class="language-csharp">int[] numbers = new int[5]; // Array with 5 elements (indices 0-4) Console.WriteLine(numbers[5]); // Throws IndexOutOfRangeException</code>>在這裡,
嘗試訪問不存在的第六個元素,從而導致錯誤。 numbers[5]
>
與其他集合一起工作
此基於零的索引適用於其他集合,包括。 最後一個可訪問的元素始終處於indexList<T>
。
Count - 1
為了安全迭代,請考慮使用A
for
<code class="language-csharp">List<string> names = new List<string> { "Alice", "Bob", "Charlie" }; for (int i = 0; i < names.Count; i++) { Console.WriteLine(names[i]); }</code>循環,該循環自動處理迭代並防止索引錯誤:
foreach
<code class="language-csharp">foreach (string name in names) { Console.WriteLine(name); }</code>防止IndexoutofRangeExceptions
避免以下例外:
>
Length - 1
Count - 1
使用Count
>屬性(用於列表)或Length
屬性(用於數組)來確定集合的大小。
Count
Length
>首選foreach
循環簡化迭代並消除了手動索引錯誤的風險。
foreach
try-catch
>
IndexOutOfRangeException
以上是為什麼我的代碼中會遇到'索引之外的範圍”錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!