关于修改集合的例外

Mik*_*ike 0 c# dictionary exception

我有以下代码迭代字典,如果键没有值,它会检查另一个字典的值并分配它.我继续得到以下异常.

- $exception {"Collection was modified; enumeration operation may not execute."} System.Exception {System.InvalidOperationException}

foreach (KeyValuePair<string, string> param in request.Field.StoredProcedure.Parameters)
{
    if ((param.Value == null || param.Value.Length == 0) &&
         request.SearchParams.ContainsKey(param.Key))
    {
        request.Field.StoredProcedure.Parameters[param.Key] =
             request.SearchParams[param.Key];
    }
    else if (param.Value == null || param.Value.Length == 0)
    {
        throw new ArgumentException(
            "No value could be found for sproc parameter " + param.Key);
    }
}
Run Code Online (Sandbox Code Playgroud)

在迭代它时,您是否无法为集合分配值?

Blo*_*ard 6

在迭代它时,您是否无法为集合分配值?

正确.试试这个:

foreach (var param in request.Field.StoredProcedure.Parameters.ToList())
{
    ...
Run Code Online (Sandbox Code Playgroud)

这是因为foreach使用了枚举器,并且..

只要集合保持不变,枚举器仍然有效.如果对集合进行了更改(例如添加,修改或删除元素),则枚举数将无法恢复,并且其行为未定义.

来源:http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.getenumerator.aspx

如果添加a .ToList(),则现在枚举该集合的副本,并且可以在不影响副本的情况下修改原始集合.