簡體   English   中英

c# foreach 循環無法在數組中添加文字

[英]c# foreach loop not able to add literals in an array

首先,我知道我不能在 C# 中使用 foreach 循環在數組中添加值......但為什么呢? 為什么例如我不能這樣做

int[] numbers = { 1, 4, 3, 5, 7, 9 };
foreach (int item in numbers)
{
    numbers[item] = 2;
}

跟后端foreach循環的實際實現有關系嗎? foreach 循環究竟是如何工作的? 我知道它遍歷整個集合(數組),但究竟是怎樣的?

您正在傳遞數組中項目的值(您的變量item將是序列中每個位置的數組值,而不是索引)作為索引。 那里使用的索引是您嘗試訪問的項目的位置,而不是值。 因此,您正在調用的循環的每次迭代:

  • numbers[1]
  • numbers[4]
  • numbers[3]
  • numbers[5]
  • numbers[7]
  • numbers[9]

該數組有 6 個數字,因此當您到達numbers[7] ,您要求的是一個不存在的值,因此是例外。

做你想做的事情的更好方法是:

for(int i = 0; i < numbers.Length; i++)
{
    numbers[i] = 2;
}

在此循環的每次迭代中,您將訪問:

  • numbers[0]
  • numbers[1]
  • numbers[2]
  • numbers[3]
  • numbers[4]
  • numbers[5]

您需要 在調試器中逐步執行您的代碼

for語句更像是while語句,而不是foreach

int[] numbers = { 1, 4, 3, 5, 7, 9 }; 創建這個:

numbers[0] = 1;
numbers[1] = 4;
numbers[2] = 3;
numbers[3] = 5;
numbers[4] = 7;
numbers[5] = 9;

您的foreach語句執行以下操作:

numbers[1] = 2;
numbers[4] = 2;
numbers[3] = 2;
numbers[5] = 2;
numbers[7] = 2; <- this line overflows your array!
numbers[9] = 2; <- and so would this.

您必須了解數組索引和數組值之間的區別。

我在看這個:

numbers[item] = 2;

在這個表達式中,您像使用索引一樣使用item變量,就好像它具有值1234等。這不是 foreach 迭代變量在 C# 中的工作方式 我知道這樣做的唯一語言是 Javascript。

請記住, foreachfor不是一回事。 幾乎所有其他語言,包括 C#,都會在foreach循環的item變量中為您提供實際的數組值: 1435等。現在,這些是整數,因此您可以嘗試將它們用作索引。 您可以像這樣運行循環一段時間...直到達到值7 此時,您的數組只有六個值。 你正在嘗試這樣做:

numbers[7] = 2;

對於可以使用的最大有效索引為5的數組。

即使考慮到您對數組的修改,情況也是如此。 讓我們看一下循環每次迭代后的數組:

{ 1, 4, 3, 5, 7, 9 }  //initial state
{ 1, 2, 3, 5, 7, 9 }  // after 1st iteration (index 0). Value at index 0 is 1, so item as index 1 is set to 2
{ 1, 2, 2, 5, 7, 9 }  // after 2nd iteration (index 1). Value at index 1 is now 2, so item at index 2 is set to 2
{ 1, 2, 2, 5, 7, 9 }  // after 3rd iteration (index 2). Value at index 2 is now 2, so item at index 2 is set to 2
{ 1, 2, 2, 5, 7, 2 }  // after 4th iteration (index 3). Value at index 3 is 5, so item at index 5 is set to 2
// The 5th iteration (index 4). Value at index 4 is 7, which is beyond the end of the array

至於為什么......聽起來你已經習慣了一種更動態的語言。 一些其他語言,如 php 或 Javascript,在純計算機科學意義上根本沒有真正的數組 相反,它們具有稱為數組的集合類型,但是當您深入了解它時,它們確實有所不同。

C#有實數數組,實數數組有固定大小。 如果您真正想要的是集合,C# 也有集合。 例如,您可以使用List<T>對象來獲取可以輕松附加到的類似數組的集合。

對於其他語言,結果因您所談論的內容而異,但對於最寬松的第 5 次迭代的結果是這樣的:

{ 1, 2, 2, 5, 7, 2,  ,2 } 

請注意索引 6 處的缺失值。這種情況會導致錯誤從測試中溜走,直到運行時才會出現。 您還需要開始考慮填充數組的密度或稀疏程度,因為處理這些數組的最佳策略可能會因您的答案而異...了解哈希表和字典的所有方式。 而且,順便說一下,C# 再次為您提供了這些選項。

您需要創建計數器,在其他情況下,您嘗試訪問數組之外​​的項目

int[] numbers = new int[]{ 1, 4, 3, 5, 7, 9 };
int i = 0;
foreach (int item in numbers)
{
    numbers[i] = 2;
    i++;
}

// Print the items of the array
foreach (int item in numbers)
{
    Console.WriteLine(item);
}

暫無
暫無

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

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