Array-Klasse

Stellt Methoden zum Erstellen, Bearbeiten, Durchsuchen und Sortieren von Arrays bereit und ist damit Basisklasse für alle Arrays in der Common Language Runtime.

Namespace: System
Assembly: mscorlib (in mscorlib.dll)

Syntax

'Declaration
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public MustInherit Class Array
    Implements ICloneable, IList, ICollection, IEnumerable
'Usage
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

Hinweise

Die Array-Klasse ist die Basisklasse für Implementierungen von Programmiersprachen, die Arrays unterstützen. Nur das System oder Compiler können jedoch explizit von der Array-Klasse ableiten. Benutzer sollten die von der Sprache zur Verfügung gestellten Arraykonstrukte verwenden.

Ein Element ist ein Wert in einem Array. Die Länge eines Array ist die Gesamtzahl von Elementen, die es enthalten kann. Der Rang eines Array ist die Anzahl von Dimensionen im Array. Die untere Grenze einer Dimension eines Array ist der Startindex dieser Dimension des Array. Ein mehrdimensionales Array kann für jede Dimension verschiedene Grenzen haben.

Wichtig

In .NET Framework, Version 2.0, implementiert die Array-Klasse die generischen Schnittstellen System.Collections.Generic.IList, System.Collections.Generic.ICollection und System.Collections.Generic.IEnumerable. Die Implementierungen werden den Arrays zur Laufzeit bereitgestellt und sind daher für Buildtools der Dokumentation nicht sichtbar. Daraus resultiert, dass die generischen Schnittstellen nicht in der Deklarationssyntax für die Array-Klasse angezeigt werden und dass es keine Verweisthemen für Schnittstellenmember gibt, auf die nur durch das Konvertieren eines Array in den generischen Schnittstellentyp (explizite Schnittstellenimplementierungen) zugegriffen werden kann. Sie sollten beim Konvertieren eines Arrays zu einer dieser Schnittstellen unbedingt beachten, dass Member, die Elemente hinzufügen, einfügen oder entfernen, eine NotSupportedException auslösen.

Informationen über Arraytypdeklarationen werden von Type-Objekten bereitgestellt. Array-Objekte desselben Arraytyps werden durch dasselbe Type-Objekt dargestellt.

Type.IsArray und Type.GetElementType geben bei Array möglicherweise nicht die erwarteten Ergebnisse zurück, da ein Array, das in den Typ Array umgewandelt wird, ein Objekt und kein Array ergibt. Das heißt, typeof(System.Array).IsArray gibt false zurück, und typeof(System.Array).GetElementType gibt NULL (Nothing in Visual Basic) zurück.

Im Unterschied zu den meisten anderen Klassen stellt Array anstelle öffentlicher Konstruktoren die CreateInstance-Methode bereit, um Zugriff mit spätem Binden zu ermöglichen.

Die Array.Copy-Methode kopiert nicht nur Elemente zwischen Arrays desselben Typs, sondern auch zwischen Standardarrays verschiedener Typen. Typen werden automatisch umgewandelt.

Zur Unterstützung von Arrays mit großer Kapazität bieten einige Methoden wie CreateInstance, Copy, CopyTo, GetValue und SetValue Überladungen, die 64-Bit-Ganzzahlen als Parameter akzeptieren. LongLength und GetLongLength geben 64-Bit-Ganzzahlen zurück, die die Länge des Arrays angeben.

Es wird nicht sichergestellt, dass die Array sortiert ist. Sie müssen die Array sortieren, bevor Sie Vorgänge wie BinarySearch durchführen, die eine sortierte Array voraussetzen.

Beispiel

Im folgenden Codebeispiel wird veranschaulicht, wie Array.Copy Elemente zwischen einem Array von ganzzahligem Typ und einem Array vom Typ Object kopiert.

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
 */

Im folgenden Codebeispiel wird ein Array erstellt und initialisiert, und es werden die Eigenschaften und Elemente angezeigt.

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
 */

Vererbungshierarchie

System.Object
  System.Array

Threadsicherheit

Öffentliche statische (Shared in Visual Basic) Member dieses Typs sind threadsicher. Bei Instanzmembern ist die Threadsicherheit nicht gewährleistet.

Diese Implementierung stellt keinen synchronisierten (threadsicheren) Wrapper für ein Array dar, jedoch können auf Array basierende .NET Framework-Klassen über die SyncRoot-Eigenschaft eine eigene synchronisierte Version der Auflistung bereitstellen.

Die Enumeration einer Auflistung ist systemintern keine threadsichere Prozedur. Selbst wenn eine Auflistung synchronisiert wird, besteht die Möglichkeit, dass andere Threads sie ändern. Dies führt dazu, dass der Enumerator eine Ausnahme auslöst. Um während der Enumeration Threadsicherheit zu gewährleisten, können Sie entweder die Auflistung während der gesamten Enumeration sperren, oder Sie können die durch andere Threads aufgrund von Änderungen ausgelösten Ausnahmen abfangen.

Plattformen

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

.NET Framework unterstützt nicht alle Versionen sämtlicher Plattformen. Eine Liste der unterstützten Versionen finden Sie unter Systemanforderungen.

Versionsinformationen

.NET Framework

Unterstützt in: 2.0, 1.1, 1.0

.NET Compact Framework

Unterstützt in: 2.0, 1.0

Siehe auch

Referenz

Array-Member
System-Namespace
Object
Type

Weitere Ressourcen

Durchführen kulturunabhängiger Zeichenfolgenoperationen in Arrays