2019-10-30 System.InvalidOperationException: 컬렉션이 수정되었습니다. 열거 작업이 실행되지 않을 수도 있습니다.

Console Programming/C# Console 2019. 10. 30. 10:03

 

새로운 Book 타입 개체를 만들어서 ArrayList에 집어넣으려고 하니 에러가 발생했다.

 

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

namespace Console1029
{
    public class App3
    {
        public App3()
        {
            // Creates and initializes a new ArrayList.
            ArrayList myAL = new ArrayList();
            myAL.Add("Hello");
            myAL.Add("1");
            myAL.Add(new Book());         
            foreach (var element in myAL)
            {
                //만약 element타입이  Book타입일 경우 Author, Title값을 추가하세요
                //Title = "Republic, The", Author = "Plato"               
                
                if (element is Book)
                {
                    Book b = element as Book;
                    b.Title = b.Title == null ? "null" : b.Title;
                    b.Author = b.Author == null ? "null" : b.Author;
                    Console.WriteLine($"Title: {b.Title} Author: {b.Author}");
                }
                else
                {
                    Console.WriteLine(element);
                }                
            }

            int i = 0;
            foreach(var element in myAL)
            {
                if (element.GetType() == typeof(Book))
                {
                    var book2 = new Book();
                    book2.Title = "Republic, The";
                    book2.Author = "Plato";
                    myAL[i] = (object)book2;
                }
                i++;
            }

            //for (int i = 0; i < myAL.Count; i++)
            //{
            //    if (myAL[i].GetType() == typeof(Book))
            //    {
            //        var book2 = new Book();
            //        book2.Title = "Republic, The";
            //        book2.Author = "Plato";
            //        myAL[i] = (object)book2;
            //    }
            //}

            foreach (var element in myAL)
            {                        
                var a = element is Book ? (Book)element : element;

                if (element.GetType() == typeof(Book))
                {
                    Book b = (Book)a;
                    b.Title = b.Title == null ? "null" : b.Title;
                    b.Author = b.Author == null ? "null" : b.Author;
                    Console.WriteLine($"Title: {b.Title} Author: {b.Author}");
                }
                else
                {
                    Console.WriteLine(a);
                }
            }
        }       
    }
}

 

 

 

 

'Console Programming > C# Console' 카테고리의 다른 글

백준 2748 피보나치수2  (0) 2019.10.31
2019-10-30 Queue<T>를 연습하는 예제  (0) 2019.10.30
백준 1003 피보나치함수  (0) 2019.10.30
백준 1773 폭죽쇼  (0) 2019.10.28
백준 1159 농구경기  (0) 2019.10.25
: