简体   繁体   中英

Index outside bounds of the array C#

I'm trying to simplify a few long statements with arrays, I've found similar questions on here but I can't work out where i'm going wrong. The code is as follows:

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
}   

The code grade[I].Enabled= false; works fine, however its only the unitselect which doesn't work, thanks if you are able to help.

Unitselect只包含17个项目,没有unitselect14

I'm not sure what your intention is with the loop logic, but since you are working with an array (which implements IEnumerable), you may be better off solving your problem using LINQ.

Example:

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

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

Update

As per @Gusdor's comment, a standard foreach loop would be better.

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

数组索引从零开始你在unitselect数组中有17个元素,所以应该是

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

The error would imply you have a different number of elements in the 2 arrays in this specific case unitselect[] . Eventually the for loop hits some value of i that exceeds the length of the array.

You missed unitselect14 element in the array. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM