ArrayList 클래스의 매개 변수 없는 ToArray 메서드는 Object 형식의 배열을 반환합니다. Object 배열을 사용자 형식의 배열로 캐스팅할 때는 ToArray의 매개 변수 없는 구현을 사용할 수 없습니다. 예를 들어 ArrayList에 Customer 개체를 몇 개 추가하면 기본 목록이 Customer 배열로 만들어지지 않습니다. 따라서 다음 문은 System.InvalidCastException 예외와 함께 실패합니다.
Customer [] customer = (Customer[])myArrayList.ToArray();
강력하게 형식화된 배열을 반환하려면 개체 형식을 매개 변수로 받아들이는 오버로드된 ToArray 메서드를 사용하십시오. 예를 들어 다음 문은 성공합니다.
Customer [] customer = (Customer[])myArrayList.ToArray(typeof(Customer));

참고: C#에서는 암시적 캐스팅이 허용되지 않으므로 ToArray 메서드의 결과를 명시적으로 캐스팅해야 합니다.

중요: ArrayList의 요소는 개체 형식이 모두 같아야 합니다. 다른 개체로 이루어진 ArrayList를 특정 형식으로 캐스팅하려고 하면 ToArray 메서드가 실패합니다.

단계별 예제

01using System;
02using System.Collections;
03 
04  class Class1
05  {  
06    [STAThread]
07    static void Main(string[] args)
08    {    
09        customer c = new customer();
10        c.cname = "anonymous";
11         
12        ArrayList al=new ArrayList();
13        al.Add(c);
14        object[] cArray = al.ToArray();
15 
16 
17        //Display the type of the ArrayList.
18        Console.WriteLine(cArray.GetType());
19        
20        //customer[] custArray = (customer[])(al.ToArray());
21 
22        //InvalidCastException 예외를 재현하려면 위의 주석문을 해제하고.
23 
24        // 아래 명령을 주석처리 하여 실행하십시오.      
25        customer[] custArray = (customer[])al.ToArray(typeof(customer));
26 
27        Console.WriteLine(custArray.GetType());     
28    }
29  }
30  class customer
31  {
32    public string cname;
33  }

출처 :  http://support.microsoft.com/
출처2: http://choiwonwoo.egloos.com/313178

Posted by 아르다