簡體   English   中英

索引數組外的邊界C#

[英]Index outside bounds of the array C#

我正在嘗試用數組簡化一些長語句,我在這里發現了類似的問題,但我無法解決我出錯的地方。 代碼如下:

if (coursechoice.Text == ("Subsidiary Diploma"))
{               
    var grade = new[] { grade1, grade2, grade3, grade4, grade5, grade6, grade7, grade8, grade9, grade10, grade11, grade12, grade13, grade14, grade15, grade16, grade17, grade18 };
    var unitselect = new[] { unitselect1, unitselect2, unitselect3, unitselect4, unitselect5, unitselect6, unitselect7, unitselect8, unitselect9, unitselect10, unitselect11, unitselect12, unitselect13, unitselect15, unitselect16, unitselect17, unitselect18 };

for (var i = 3; i < 18; i++)
{                   
    grade[i].Enabled = false;
    unitselect[i].Enabled = false; // I get index out of bounds of the array here
}   

代碼grade[I].Enabled= false; 工作正常,但它只是單位選擇不起作用,謝謝你能夠提供幫助。

Unitselect只包含17個項目,沒有unitselect14

我不確定你對循環邏輯的意圖是什么,但是因為你正在使用一個數組(實現IEnumerable),你可能最好使用LINQ來解決你的問題。

例:

grade.Skip(4).Take(15).ToList().ForEach(g => g.Enabled = false);

Linq docs: http//msdn.microsoft.com/en-us/library/vstudio/bb397926.aspx

更新

根據@ Gusdor的評論,標准的foreach循環會更好。

foreach(var g in grade.Skip(4).Take(15)) { 
    g.Enabled = false; 
} 

數組索引從零開始你在unitselect數組中有17個元素,所以應該是

        for (var i = 3; i < 17; i++)

該錯誤意味着在這個特定情況下,2個數組中有不同數量的元素unitselect[] 最終for循環命中i的某個值超過了數組的長度。

你錯過了數組中的unitselect14元素。 :)

暫無
暫無

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

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