'배열변환'에 해당되는 글 1건

  1. 2009.10.05 C# ToArray(type) 메서드에서 강력하게 형식화된 배열 반환 by 아르다

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 메서드가 실패합니다.

단계별 예제

using System;
using System.Collections;

  class Class1
  {   
    [STAThread]
    static void Main(string[] args)
    {     
        customer c = new customer();
        c.cname = "anonymous";
        
        ArrayList al=new ArrayList();
        al.Add(c);
        object[] cArray = al.ToArray();


        //Display the type of the ArrayList.
        Console.WriteLine(cArray.GetType());
       
        //customer[] custArray = (customer[])(al.ToArray());

        //InvalidCastException 예외를 재현하려면 위의 주석문을 해제하고.

        // 아래 명령을 주석처리 하여 실행하십시오.       
        customer[] custArray = (customer[])al.ToArray(typeof(customer));

        Console.WriteLine(custArray.GetType());      
    }
  }
  class customer
  {
    public string cname;
  }

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

Posted by 아르다