未处理的异常:System.InvalidOperationException:集合已被修改;枚举可能无法执行

时间:2014-04-11 13:12:26

标签: c#-4.0

我创建了添加,删除和修改添加到arraylist的对象的代码。当我选择remove方法时,它显示上面的error.how我能解决它。这段代码是我运行的所有东西。它有一个实例具有所有必要方法的成员类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MedicalAid
{
class MedicalTest
{

    //instance of MedicalTest class
    public static MedicalTest medicalMember = new MedicalTest();
    //array list to hold member objects
    static List<Member> customer = new List<Member>();
    //instance of Member class
    static Member member = new Member();
    //some important booleans
    private bool isSubscribed;
    private bool isDeducted;
    private bool isToBeRemoved;
    private bool isToBeAdded = true;


    //add passed memebers to arraylist
    public void addMembersToArrayList()
    {
        customer.Add(member1);
        customer.Add(member2);
        isToBeAdded = false;
    }
    //method to add member
     public void AddMember(Member name)
       {
         customer.Add(name);
       }

    //method to remove a member
     public  void RemoveMember(String removeName) {
        foreach (Member i in customer) {

            if (isToBeRemoved)
            {
                if (i.GetName() == removeName)
                {
                    Console.WriteLine("Found and Removed");
                    customer.Remove(i);

                }
                else{Console.WriteLine("Not Found");}
            }


        if(isSubscribed)
        {
        if (i.GetName() == removeName) 
        {
            //if delete member is true,delete member
               Console.WriteLine("Found and Transaction Made");
            i.makeSubscription();
            i.showMember();
            }//closes isToBeDeleted
        else { Console.WriteLine("Not Found"); }
        }

        if(isDeducted){
            if (i.GetName() == removeName)
            {
            //if delete member is true,delete member
            Console.WriteLine("Found and Transaction Made");
             i.makeSubscription();
             i.showMember();
            }//closes isToBeDeleted
            else
            {
                Console.WriteLine("Not Found"); 
            }
        }//closes deducted if
    }

}

    //method to iterate through customer and remove a member
     public void ViewMembers()
     {

        //iterate throus the customer list and print details of any member availabe    
              if(customer.Capacity == 0){
              Console.WriteLine("Medical Aid List is Empty");
              }else{  
              foreach(Member i in customer){
                  i.showMember();
              }
              }
     }

     //create two objects with details
     Member member1 = new Member("male",
                   "Z.N.A",
                   " 272 Area 3 D/Mvura Mutare",
                   "Premium",
                       "JAMES",
                       500.00,
                       "Dr Bvirakure",
                       "xx-xxxxx y XX",
         //spouse
                       "xx/xx/1987",
                       "JOSEPHINE MANYORE",
                       "XX-XXXXX-XX",
         //family doctor
                       "DANGAMVURA SHOPPING MALL",
                   "0773 0733 0734",
         //dependent
                       "male",
                       "ANDREW BLESSING MANYORE",
                       "75-426820 Y 50",
         //bank details
                       "ZABG",
                   "Herbet Chitepo",
                   "xxxxxxxxxxxxx",
                   "xxxxxxxxxxxxx",
                       "Mutare");
     Member member2 = new Member("female",
                   "MINISTRY OF EDUCATION",
                   " 272 Area 3 D/Mvura Mutare",
                   "Premium",
                       "TAPIWA",
                       500.00,
                       "Dr Bvirakure",
                       "xx-xxxxx y XX",
         //spouse
                       "xx/xx/1987",
                       "JAMES MANYORE",
                       "XX-XXXXX-XX",
         //family doctor
                       "DANGAMVURA SHOPPING MALL",
                   "0773 0733 0734",
         //dependent
                       "male",
                       "PORTIA TATENDA MANYORE",
                       "75-426820 Y 50",
         //bank details
                       "ZB",
                   "Herbet Chitepo",
                   "xxxxxxxxxxxxx",
                   "xxxxxxxxxxxxx",
                       "Mutare");
     //method to print saved members


    static void Main(string[] args)
    {
         int option;
         string options;
         //add the members to the arraylist
         if (medicalMember.isToBeAdded)
         {
             medicalMember.addMembersToArrayList();
         }

    do{
       Console.Write("********Medical Aid*********\n"+
                         "1.To Add New Member\n"+
                         "2.To Edit Member Balance if he made a Subscription\n" +
                         "3.To Edit Member Balance if he received a Service\n" +
                         "4.To Delete Old Member\n" +
                         "5.To View Members\n"+
                         "6.To Exit\n"); 
      options = Console.ReadLine();
      option = Convert.ToInt32(options);

      switch(option){

      case 1: member.GetMember();
              medicalMember.AddMember(member);

              break;

     case 2 : medicalMember.isSubscribed = true;
              medicalMember.isDeducted = false;
              medicalMember.isToBeRemoved = false;
              Console.WriteLine("Enter Member Name who made a Subscription\n");
              String memberToGetSer = Console.ReadLine();
              medicalMember.RemoveMember(memberToGetSer);
              break;

      case 3 :medicalMember.isSubscribed = false;
              medicalMember.isDeducted = true;
              medicalMember.isToBeRemoved = false;
              Console.WriteLine("Enter Member Name who received a Service\n");
              String memberToGetSub = Console.ReadLine();
              medicalMember.RemoveMember(memberToGetSub);
              break;

      case 4: medicalMember.isSubscribed = false;
              medicalMember.isDeducted = false;
              medicalMember.isToBeRemoved = true;
              Console.WriteLine("Enter Member Name to remove");
              String memberToRemove = Console.ReadLine();
              medicalMember.RemoveMember(memberToRemove);

              break;

      case 5: medicalMember.ViewMembers();
              break;

      case 6:  Console.WriteLine("******EXITING********");
              Environment.Exit(0);
              break;
        }//closes switch
      }while(option<=5);//closes while
    }//closes main
}//closes class
}

2 个答案:

答案 0 :(得分:0)

如果您正在通过集合向前阅读,则无法删除元素,因为枚举器将无效。尝试使用RemoveAll方法,它将执行您想要的操作并简化代码:

if (isToBeRemoved) // No need for a for loop.
{
    customer.RemoveAll(elem => elem.GetName() == removeName);
}

答案 1 :(得分:0)

你不能在Remove()内召唤foreach loop(只要它涉及你正在循环的集合)

使用for循环:

for (int i=0;i<customer.Count;i++)
{
    ......
}

来自MSDN:

     The foreach statement is used to iterate through the collection to get the information that you want,
 but can not be used to add or remove items from the source collection to avoid unpredictable side effects.
 If you need to add or remove items from the source collection, use a for loop.

有关详细信息,请参阅this

只需在删除成员中更改此内容:

public  void RemoveMember(String removeName) {
    for (int i=customer.Count - 1;i>=0;i--) {
        if (isToBeRemoved)
        {
            if (customer[i].GetName() == removeName)
            {
                Console.WriteLine("Found and Removed");
                customer.RemoveAt(i);
            }
            else{Console.WriteLine("Not Found");
        }
    }
}