Array 클래스

배열을 만들고, 조작하고, 검색 및 정렬하여 공용 언어 런타임에서 모든 배열의 기본 클래스 역할을 수행하도록 하는 메서드를 제공합니다.

네임스페이스: System
어셈블리: mscorlib(mscorlib.dll)

구문

‘선언
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public MustInherit Class Array
    Implements ICloneable, IList, ICollection, IEnumerable
‘사용 방법
Dim instance As Array
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public abstract class Array : ICloneable, IList, ICollection, 
    IEnumerable
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public ref class Array abstract : ICloneable, IList, ICollection, 
    IEnumerable
/** @attribute SerializableAttribute() */ 
/** @attribute ComVisibleAttribute(true) */ 
public abstract class Array implements ICloneable, IList, 
    ICollection, IEnumerable
SerializableAttribute 
ComVisibleAttribute(true) 
public abstract class Array implements ICloneable, IList, 
    ICollection, IEnumerable

설명

Array 클래스는 배열을 지원하는 언어 구현의 기본 클래스입니다. 그러나 Array 클래스에서는 시스템 및 컴파일러만 명시적으로 파생시킬 수 있습니다. 사용자는 언어에서 제공되는 배열 구문을 사용해야 합니다.

요소는 Array의 값입니다. Array의 길이는 포함할 수 있는 요소의 총수입니다. Array의 차수는 Array의 차원 수입니다. Array의 차원에 대한 하한은 Array의 해당 차원에 대한 시작 인덱스이지만 다차원 Array에는 각 차원에 대해 서로 다른 범위를 지정할 수 있습니다.

중요

.NET Framework 버전 2.0에서 Array 클래스는 System.Collections.Generic.IList, System.Collections.Generic.ICollectionSystem.Collections.Generic.IEnumerable 제네릭 인터페이스를 구현합니다. 이 구현은 런타임에 배열에 제공되므로 설명서 빌드 도구에서는 볼 수 없습니다. 따라서 제네릭 인터페이스는 Array 클래스의 선언 구문에 표시되지 않으며, 배열을 제네릭 인터페이스 형식으로 캐스팅(명시적 인터페이스 구현)해야만 액세스할 수 있는 인터페이스 멤버에 대한 참조 항목은 없습니다. 배열을 이러한 인터페이스 중 하나로 캐스팅할 때 알아 두어야 할 중요한 점은 요소를 추가, 삽입 또는 제거하는 멤버에서 NotSupportedException을 throw한다는 것입니다.

Type 개체는 배열 형식 선언에 대한 정보를 제공합니다. 배열 형식이 같은 Array 개체는 같은 Type 개체를 공유합니다.

Array에서 Type.IsArrayType.GetElementType을 사용하면 예기치 않은 결과가 반환될 수 있습니다. 배열이 Array 형식으로 변환되면 결과는 배열이 아니라 개체이기 때문입니다. 즉, typeof(System.Array).IsArrayfalse를 반환하고, typeof(System.Array).GetElementType은 Null 참조(Visual Basic의 경우 Nothing)를 반환합니다.

대부분의 클래스와 달리 Array는 런타임 바인딩 액세스를 허용하는 공용 생성자 대신 CreateInstance 메서드를 제공합니다.

Array.Copy 메서드는 형식이 같은 배열뿐만 아니라 형식이 다른 표준 배열 간에도 요소를 복사하며 형식 캐스팅을 자동으로 처리합니다.

CreateInstance, Copy, CopyTo, GetValueSetValue 같은 메서드는 대용량 배열을 수용할 수 있도록 64비트 정수를 매개 변수로 받아들이는 오버로드를 제공하며, LongLengthGetLongLength는 해당 배열의 길이를 나타내는 64비트 정수를 반환합니다.

Array는 정렬되어 있지 않을 수 있으므로 Array가 정렬되어 있어야 하는 BinarySearch와 같은 작업을 수행하기 전에는 Array를 정렬해야 합니다.

예제

다음 코드 예제에서는 Array.Copy를 사용하여 정수 형식의 배열과 Object 형식의 배열 간에 요소를 복사하는 방법을 설명합니다.

Public Class SamplesArray    
    
    Public Shared Sub Main()
        
        ' Creates and initializes a new integer array and a new Object array.
        Dim myIntArray() As Integer = {1, 2, 3, 4, 5}
        Dim myObjArray() As Object = {26, 27, 28, 29, 30}
        
        ' Prints the initial values of both arrays.
        Console.WriteLine("Initially,")
        Console.Write("integer array:")
        PrintValues(myIntArray)
        Console.Write("Object array: ")
        PrintValues(myObjArray)
        
        ' Copies the first two elements from the integer array to the Object array.
        Array.Copy(myIntArray, myObjArray, 2)
        
        ' Prints the values of the modified arrays.
        Console.WriteLine(ControlChars.NewLine + "After copying the first two" _
           + " elements of the integer array to the Object array,")
        Console.Write("integer array:")
        PrintValues(myIntArray)
        Console.Write("Object array: ")
        PrintValues(myObjArray)
        
        ' Copies the last two elements from the Object array to the integer array.
        Array.Copy(myObjArray, myObjArray.GetUpperBound(0) - 1, myIntArray, _
           myIntArray.GetUpperBound(0) - 1, 2)
        
        ' Prints the values of the modified arrays.
        Console.WriteLine(ControlChars.NewLine + "After copying the last two" _
           + " elements of the Object array to the integer array,")
        Console.Write("integer array:")
        PrintValues(myIntArray)
        Console.Write("Object array: ")
        PrintValues(myObjArray)
    End Sub
    
    Overloads Public Shared Sub PrintValues(myArr() As Object)
        Dim i As Object
        For Each i In  myArr
            Console.Write(ControlChars.Tab + "{0}", i)
        Next i
        Console.WriteLine()
    End Sub    
    
    Overloads Public Shared Sub PrintValues(myArr() As Integer)
        Dim i As Integer
        For Each i In  myArr
            Console.Write(ControlChars.Tab + "{0}", i)
        Next i
        Console.WriteLine()
    End Sub
End Class

' This code produces the following output.
' 
' Initially,
' integer array:  1       2       3       4       5
' Object array:   26      27      28      29      30
' 
' After copying the first two elements of the integer array to the Object array,
' integer array:  1       2       3       4       5
' Object array:   1       2       28      29      30
' 
' After copying the last two elements of the Object array to the integer array,
' integer array:  1       2       3       29      30
' Object array:   1       2       28      29      30
public class SamplesArray  {

   public static void Main()  {

      // Creates and initializes a new integer array and a new Object array.
      int[] myIntArray = new int[5] { 1, 2, 3, 4, 5 };
      Object[] myObjArray = new Object[5] { 26, 27, 28, 29, 30 };

      // Prints the initial values of both arrays.
      Console.WriteLine( "Initially," );
      Console.Write( "integer array:" );
      PrintValues( myIntArray );
      Console.Write( "Object array: " );
      PrintValues( myObjArray );

      // Copies the first two elements from the integer array to the Object array.
      Array.Copy( myIntArray, myObjArray, 2 );

      // Prints the values of the modified arrays.
      Console.WriteLine( "\nAfter copying the first two elements of the integer array to the Object array," );
      Console.Write( "integer array:" );
      PrintValues( myIntArray );
      Console.Write( "Object array: " );
      PrintValues( myObjArray );

      // Copies the last two elements from the Object array to the integer array.
      Array.Copy( myObjArray, myObjArray.GetUpperBound(0) - 1, myIntArray, myIntArray.GetUpperBound(0) - 1, 2 );

      // Prints the values of the modified arrays.
      Console.WriteLine( "\nAfter copying the last two elements of the Object array to the integer array," );
      Console.Write( "integer array:" );
      PrintValues( myIntArray );
      Console.Write( "Object array: " );
      PrintValues( myObjArray );
   }


   public static void PrintValues( Object[] myArr )  {
      foreach ( Object i in myArr )  {
         Console.Write( "\t{0}", i );
      }
      Console.WriteLine();
   }

   public static void PrintValues( int[] myArr )  {
      foreach ( int i in myArr )  {
         Console.Write( "\t{0}", i );
      }
      Console.WriteLine();
   }
}
/* 
This code produces the following output.

Initially,
integer array:  1       2       3       4       5
Object array:   26      27      28      29      30

After copying the first two elements of the integer array to the Object array,
integer array:  1       2       3       4       5
Object array:   1       2       28      29      30

After copying the last two elements of the Object array to the integer array,
integer array:  1       2       3       29      30
Object array:   1       2       28      29      30
*/
using namespace System;
void main1();
void main2();
void main()
{
   main1();
   Console::WriteLine();
   main2();
}

void PrintValues( array<Object^>^myArr );
void PrintValues( array<int>^myArr );
void main1()
{
   // Creates and initializes a new int array and a new Object array.
   array<int>^myIntArray = {1,2,3,4,5};
   array<Object^>^myObjArray = {26,27,28,29,30};

   // Prints the initial values of both arrays.
   Console::WriteLine(  "Initially," );
   Console::Write(  "int array:   " );
   PrintValues( myIntArray );
   Console::Write(  "Object array:" );
   PrintValues( myObjArray );

   // Copies the first two elements from the int array to the Object array.
   Array::Copy( myIntArray, myObjArray, 2 );

   // Prints the values of the modified arrays.
   Console::WriteLine(  "\nAfter copying the first two elements of the int array to the Object array," );
   Console::Write(  "int array:   " );
   PrintValues( myIntArray );
   Console::Write(  "Object array:" );
   PrintValues( myObjArray );

   // Copies the last two elements from the Object array to the int array.
   Array::Copy( myObjArray, myObjArray->GetUpperBound( 0 ) - 1, myIntArray, myIntArray->GetUpperBound( 0 ) - 1, 2 );

   // Prints the values of the modified arrays.
   Console::WriteLine(  "\nAfter copying the last two elements of the Object array to the int array," );
   Console::Write(  "int array:   " );
   PrintValues( myIntArray );
   Console::Write(  "Object array:" );
   PrintValues( myObjArray );
}

void PrintValues( array<Object^>^myArr )
{
   for ( int i = 0; i < myArr->Length; i++ )
   {
      Console::Write(  "\t{0}", myArr[ i ] );

   }
   Console::WriteLine();
}

void PrintValues( array<int>^myArr )
{
   for ( int i = 0; i < myArr->Length; i++ )
   {
      Console::Write(  "\t{0}", myArr[ i ] );

   }
   Console::WriteLine();
}


/* 
 This code produces the following output.
 
 Initially,
 int array:       1    2    3    4    5
 Object array:    26    27    28    29    30
 After copying the first two elements of the int array to the Object array,
 int array:       1    2    3    4    5
 Object array:    1    2    28    29    30
 After copying the last two elements of the Object array to the int array,
 int array:       1    2    3    29    30
 Object array:    1    2    28    29    30
 */
public class SamplesArray
{
    public static void main(String[] args)
    {
        // Creates and initializes a new integer array and a new Object array.
        int myIntArray[] = new int[] { 1, 2, 3, 4, 5 };
        Object myObjArray[] = new Object[] { (Int32)26, (Int32)27, (Int32)28, 
            (Int32)29, (Int32)30};
        // Prints the initial values of both arrays.
        Console.WriteLine("Initially,");
        Console.Write("integer array:");
        PrintValues(myIntArray);
        Console.Write("Object array: ");
        PrintValues(myObjArray);
        // Copies the first two elements from the integer array to the 
        // Object array.
        Array.Copy(myIntArray, myObjArray, 2);
        // Prints the values of the modified arrays.
        Console.WriteLine("\nAfter copying the first two elements of the"
            + " integer array to the Object array,");
        Console.Write("integer array:");
        PrintValues(myIntArray);
        Console.Write("Object array: ");
        PrintValues(myObjArray);
        // Copies the last two elements from the Object array to the
        // integer array.
        Array.Copy(myObjArray, myObjArray.GetUpperBound(0) - 1, myIntArray, 
            myIntArray.GetUpperBound(0) - 1, 2);
        // Prints the values of the modified arrays.
        Console.WriteLine("\nAfter copying the last two elements of the Object"
            + " array to the integer array,");
        Console.Write("integer array:");
        PrintValues(myIntArray);
        Console.Write("Object array: ");
        PrintValues(myObjArray);
    } //main

    public static void PrintValues(Object myArr[])
    {
        Object i = null;
        for (int iCtr = 0; iCtr < myArr.get_Length(); iCtr++) {
            i = myArr[iCtr];
            Console.Write("\t{0}", i);
        }
        Console.WriteLine();
    } //PrintValues

    public static void PrintValues(int myArr[])
    { 
        int i = 0;
        for (int iCtr = 0; iCtr < myArr.get_Length(); iCtr++) {
            i = myArr[iCtr];
            Console.Write("\t{0}", (Int32)i);
        }
        Console.WriteLine();
    } //PrintValues
} //SamplesArray

/* 
 This code produces the following output.
 
 Initially,
 integer array:  1       2       3       4       5
 Object array:   26      27      28      29      30

 After copying the first two elements of the integer array to the Object array,
 integer array:  1       2       3       4       5
 Object array:   1       2       28      29      30

 After copying the last two elements of the Object array to the integer array,
 integer array:  1       2       3       29      30
 Object array:   1       2       28      29      30
 */

다음 코드 예제에서는 Array를 만들고 초기화한 다음 해당 속성 및 요소를 표시합니다.

Public Class SamplesArray2    
    
    Public Shared Sub Main()
        
        ' Creates and initializes a new three-dimensional Array of
        ' type Int32.
        Dim myArr As Array = Array.CreateInstance(GetType(Int32), 2, 3, 4)
        Dim i As Integer
        For i = myArr.GetLowerBound(0) To myArr.GetUpperBound(0)
            Dim j As Integer
            For j = myArr.GetLowerBound(1) To myArr.GetUpperBound(1)
                Dim k As Integer
                For k = myArr.GetLowerBound(2) To myArr.GetUpperBound(2)
                    myArr.SetValue(i * 100 + j * 10 + k, i, j, k)
                Next k
            Next j 
        Next i ' Displays the properties of the Array.
        Console.WriteLine("The Array has {0} dimension(s) and a " _
           + "total of {1} elements.", myArr.Rank, myArr.Length)
        Console.WriteLine(ControlChars.Tab + "Length" + ControlChars.Tab _
           + "Lower" + ControlChars.Tab + "Upper")
        For i = 0 To myArr.Rank - 1
            Console.Write("{0}:" + ControlChars.Tab + "{1}", i, _
               myArr.GetLength(i))
            Console.WriteLine(ControlChars.Tab + "{0}" + ControlChars.Tab _
               + "{1}", myArr.GetLowerBound(i), myArr.GetUpperBound(i))
        Next i
        
        ' Displays the contents of the Array.
        Console.WriteLine("The Array contains the following values:")
        PrintValues(myArr)
    End Sub
    
    Public Shared Sub PrintValues(myArr As Array)
        Dim myEnumerator As System.Collections.IEnumerator = _
           myArr.GetEnumerator()
        Dim i As Integer = 0
        Dim cols As Integer = myArr.GetLength(myArr.Rank - 1)
        While myEnumerator.MoveNext()
            If i < cols Then
                i += 1
            Else
                Console.WriteLine()
                i = 1
            End If
            Console.Write(ControlChars.Tab + "{0}", myEnumerator.Current)
        End While
        Console.WriteLine()
    End Sub
End Class

' This code produces the following output.
' 
' The Array has 3 dimension(s) and a total of 24 elements.
'     Length    Lower    Upper
' 0:    2    0    1
' 1:    3    0    2
' 2:    4    0    3
' The Array contains the following values:
'     0    1    2    3
'     10    11    12    13
'     20    21    22    23
'     100    101    102    103
'     110    111    112    113
'     120    121    122    123 
public class SamplesArray2{

   public static void Main()  {

      // Creates and initializes a new three-dimensional Array of type Int32.
      Array myArr = Array.CreateInstance( typeof(Int32), 2, 3, 4 );
      for ( int i = myArr.GetLowerBound(0); i <= myArr.GetUpperBound(0); i++ )
         for ( int j = myArr.GetLowerBound(1); j <= myArr.GetUpperBound(1); j++ )
            for ( int k = myArr.GetLowerBound(2); k <= myArr.GetUpperBound(2); k++ )  {
               myArr.SetValue( (i*100)+(j*10)+k, i, j, k );
            }

      // Displays the properties of the Array.
      Console.WriteLine( "The Array has {0} dimension(s) and a total of {1} elements.", myArr.Rank, myArr.Length );
      Console.WriteLine( "\tLength\tLower\tUpper" );
      for ( int i = 0; i < myArr.Rank; i++ )  {
         Console.Write( "{0}:\t{1}", i, myArr.GetLength(i) );
         Console.WriteLine( "\t{0}\t{1}", myArr.GetLowerBound(i), myArr.GetUpperBound(i) );
      }

      // Displays the contents of the Array.
      Console.WriteLine( "The Array contains the following values:" );
      PrintValues( myArr );
   }


   public static void PrintValues( Array myArr )  {
      System.Collections.IEnumerator myEnumerator = myArr.GetEnumerator();
      int i = 0;
      int cols = myArr.GetLength( myArr.Rank - 1 );
      while ( myEnumerator.MoveNext() )  {
         if ( i < cols )  {
            i++;
         } else  {
            Console.WriteLine();
            i = 1;
         }
         Console.Write( "\t{0}", myEnumerator.Current );
      }
      Console.WriteLine();
   }
}
/* 
This code produces the following output.

The Array has 3 dimension(s) and a total of 24 elements.
    Length    Lower    Upper
0:    2    0    1
1:    3    0    2
2:    4    0    3
The Array contains the following values:
    0    1    2    3
    10    11    12    13
    20    21    22    23
    100    101    102    103
    110    111    112    113
    120    121    122    123
*/
void PrintValues( Array^ myArr );
void main2()
{
   // Creates and initializes a new three-dimensional Array instance of type Int32.
   Array^ myArr = Array::CreateInstance( Int32::typeid, 2, 3, 4 );
   for ( int i = myArr->GetLowerBound( 0 ); i <= myArr->GetUpperBound( 0 ); i++ )
   {
      for ( int j = myArr->GetLowerBound( 1 ); j <= myArr->GetUpperBound( 1 ); j++ )
      {
         for ( int k = myArr->GetLowerBound( 2 ); k <= myArr->GetUpperBound( 2 ); k++ )
            myArr->SetValue( (i * 100) + (j * 10) + k, i, j, k );

      }
   }
   
   // Displays the properties of the Array.
   Console::WriteLine(  "The Array instance has {0} dimension(s) and a total of {1} elements.", myArr->Rank, myArr->Length );
   Console::WriteLine(  "\tLength\tLower\tUpper" );
   for ( int i = 0; i < myArr->Rank; i++ )
   {
      Console::Write(  "{0}:\t{1}", i, myArr->GetLength( i ) );
      Console::WriteLine(  "\t{0}\t{1}", myArr->GetLowerBound( i ), myArr->GetUpperBound( i ) );

   }
   Console::WriteLine(  "The Array instance contains the following values:" );
   PrintValues( myArr );
}

void PrintValues( Array^ myArr )
{
   System::Collections::IEnumerator^ myEnumerator = myArr->GetEnumerator();
   int i = 0;
   int cols = myArr->GetLength( myArr->Rank - 1 );
   while ( myEnumerator->MoveNext() )
   {
      if ( i < cols )
            i++;
      else
      {
         Console::WriteLine();
         i = 1;
      }

      Console::Write(  "\t{0}", myEnumerator->Current );
   }

   Console::WriteLine();
}

/* 
 This code produces the following output.
 
 The Array instance has 3 dimension(s) and a total of 24 elements.
     Length    Lower    Upper
 0:    2    0    1
 1:    3    0    2
 2:    4    0    3
 The Array instance contains the following values:
     0    1    2    3
     10    11    12    13
     20    21    22    23
     100    101    102    103
     110    111    112    113
     120    121    122    123
 */
public class SamplesArray2
{
    public static void main(String[] args)
    {
        // Creates and initializes a new three-dimensional Array of type Int32.
        Array myArr = Array.CreateInstance(Int32.class.ToType(), 2, 3, 4);
        for (int i = myArr.GetLowerBound(0); i <= myArr.GetUpperBound(0); i++) {
            for (int j = myArr.GetLowerBound(1); j <= myArr.GetUpperBound(1);
                j++) {
                for (int k = myArr.GetLowerBound(2); k <= myArr.
                    GetUpperBound(2); k++) {
                    myArr.SetValue((Int32)(i * 100 + j * 10 + k), i, j, k);
                }
            }
        }  // Displays the properties of the Array.
        Console.WriteLine("The Array has {0} dimension(s) and a total of"
            + " {1} elements.", System.Convert.ToString(myArr.get_Rank()), 
            System.Convert.ToString(myArr.get_Length()));
        Console.WriteLine("\tLength\tLower\tUpper");
        for (int i = 0; i < myArr.get_Rank(); i++) {
            Console.Write("{0}:\t{1}", System.Convert.ToString(i), 
                System.Convert.ToString(myArr.GetLength(i)));
            Console.WriteLine("\t{0}\t{1}", System.Convert.ToString(myArr.
                GetLowerBound(i)), System.Convert.ToString(myArr.
                GetUpperBound(i)));
        }
        // Displays the contents of the Array.
        Console.WriteLine("The Array contains the following values:");
        PrintValues(myArr);
    } //main

    public static void PrintValues(Array myArr)
    {
        System.Collections.IEnumerator myEnumerator = myArr.GetEnumerator();
        int i = 0;
        int cols = myArr.GetLength(myArr.get_Rank() - 1);
        while (myEnumerator.MoveNext()) {
            if (i < cols) {
                i++;
            }
            else {
                Console.WriteLine();
                i = 1;
            }
            Console.Write("\t{0}", myEnumerator.get_Current());
        }
        Console.WriteLine();
    } //PrintValues
} //SamplesArray2

/* 
 This code produces the following output.
 
 The Array has 3 dimension(s) and a total of 24 elements.
     Length    Lower    Upper
 0:    2    0    1
 1:    3    0    2
 2:    4    0    3
 The Array contains the following values:
     0    1    2    3
     10    11    12    13
     20    21    22    23
     100    101    102    103
     110    111    112    113
     120    121    122    123
 */

상속 계층 구조

System.Object
  System.Array

스레드로부터의 안전성

이 형식의 public static(Visual Basic의 경우 Shared) 멤버는 스레드로부터 안전합니다. 모든 인스턴스 멤버는 스레드로부터 안전하지 않을 수 있습니다.

이 구현에서는 Array에 대해 동기화되어 스레드로부터 안전하게 보호되는 래퍼를 제공하지 않지만 Array를 기반으로 하는 .NET Framework 클래스에서는 SyncRoot 속성을 사용하여 해당 컬렉션의 자체 동기화 버전을 제공합니다.

컬렉션을 열거하는 프로시저는 기본적으로 스레드로부터 안전하지 않습니다. 컬렉션이 동기화되어 있을 때 다른 스레드에서 해당 컬렉션을 수정할 수 있으므로 이렇게 되면 열거자에서 예외가 throw됩니다. 열거하는 동안 스레드로부터 안전을 보장하려면 전체 열거를 수행하는 동안 컬렉션을 잠그거나 다른 스레드에서 변경된 내용으로 인해 발생한 예외를 catch하면 됩니다.

플랫폼

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

2.0, 1.1, 1.0에서 지원

.NET Compact Framework

2.0, 1.0에서 지원

참고 항목

참조

Array 멤버
System 네임스페이스
Object
Type

기타 리소스

배열에서 Culture의 영향을 받지 않는 문자열 작업 수행