-2

我一直在使用 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 在 cntr 超出数组范围之前就中断了,对吧?

4

1 回答 1

2

您为 分配的空间太少currentRestrictionKeys。但是您根本不需要预先分配它;您可以只使用 LINQ 的简单投影:

var currentRestrictionKeys = this.admingroupRepository.Context.AdminRestrictions
                                 .Select(r => r.Key)
                                 .ToArray();
于 2013-05-18T19:57:14.243 回答