递增变量的越界异常

本文关键字:越界 异常 变量 | 更新日期: 2023-09-27 18:14:10

我已经离开c#和MVC了。我真的很纠结下面的错误,我真的看不出来。我有一个限制列表,我想将它们的键添加到字符串[]。

int cntr = 0;
//loop through restrictions and add to array
foreach (var Restriction in this.admingroupRepository.Context.AdminRestrictions.ToList())
{
    currentRestrictionKeys[cntr] = Restriction.Key;
    cntr += 1;
}

这是我在cntr += 1行得到的错误:

Index was outside the bounds of the array.

我不明白这是从哪里来的,foreach在中心超出数组的边界之前中断,对吗?

递增变量的越界异常

您为currentRestrictionKeys分配的空间太少了。但你根本不需要预先分配;你可以在LINQ:

中使用一个简单的投影
var currentRestrictionKeys = this.admingroupRepository.Context.AdminRestrictions
                                 .Select(r => r.Key)
                                 .ToArray();