[펌] ToArray(type) 메서드에서 강력하게 형식화된 배열 반환

  • Post author:
  • Post category:
  • Post comments:0 Comments
  • Post last modified:January 13, 2005

Framework 2.0에서는 C++에서의 템플릿과 같은 것이 제공되던데, 이것으로 이보다 나은 모듈 설계가 가능할 것 같군요

출처: 눈물빛의 자유공간

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/

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.