集合被修改枚举操作可能无法执行VB .net

时间:2014-12-10 03:11:49

标签: asp.net vb.net

我有一个Sub Procedure接受过滤的用户集合作为参数,我想从该集合中获取userID的值,我可以看到它成功添加了第一个userID但是在Next中它引发了一个异常。

  Private Sub GetUserID(ByRef filteredusers As Business.HR.UserCollection)
  If filteredusers IsNot Nothing Then
   For Each uIDs As Business.HR.User In filteredusers
      filteredusers.Add(uIDs.UserId)
    Next 
    'exception here as System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
  End If
  End Sub

请帮助

1 个答案:

答案 0 :(得分:1)

您获得此例外的原因是您正在修改您正在迭代的收藏品。

您有几个选择:

1.  Create a separate variable to store the values in. 

  Private Sub GetUserID(ByRef filteredusers As Business.HR.UserCollection)
          dim myFilter as new Business.HR.UserCollection
          If filteredusers IsNot Nothing Then
                For Each uIDs As Business.HR.User In filteredusers
                    myFilter.Add(uIDs.UserId)
                  Next 

          End If
          filteredusers = myFilter
  End Sub
  1. 指定一个单独的变量进行迭代。

      Private Sub GetUserID(ByRef filteredusers As Business.HR.UserCollection)
              dim myFilter as Business.HR.UserCollection = filteredusers
              If filteredusers IsNot Nothing Then
                    For Each uIDs As Business.HR.User In myFilter
                        filteredusers.Add(uIDs.UserId)
                      Next              
              End If                 
      End Sub