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 的各个维度可以有不同的界限。

Note重要事项:

在 .NET Framework 2.0 版中,Array 类实现 System.Collections.Generic.IListSystem.Collections.Generic.ICollectionSystem.Collections.Generic.IEnumerable 泛型接口。由于实现是在运行时提供给数组的,因而对于文档生成工具不可见。因此,泛型接口不会出现在 Array 类的声明语法中,也不会有关于只能通过将数组强制转换为泛型接口类型(显式接口实现)才可访问的接口成员的参考主题。将某一数组强制转换为这三种接口之一时需要注意的关键一点是,添加、插入或移除元素的成员会引发 NotSupportedException

Type 对象提供有关数组类型声明的信息。具有相同数组类型的 Array 对象共享同一 Type 对象。

Type.IsArrayType.GetElementType 可能不返回所预期的 Array 形式的结果,因为如果某个数组被强制转换为 Array 类型,则结果是对象,而非数组。即,typeof(System.Array).IsArray 返回 false,而 typeof(System.Array).GetElementType 返回 空引用(在 Visual Basic 中为 Nothing)。

与大多数类不同,Array 提供 CreateInstance 方法,以便允许后期绑定访问,而不是提供公共构造函数。

Array.Copy 方法不仅可在同一类型的数组之间复制元素,而且可在不同类型的标准数组之间复制元素;它会自动处理强制类型转换。

有些方法,如 CreateInstanceCopyCopyToGetValueSetValue,提供重载(接受 64 位整数作为参数),以适应大容量数组。LongLengthGetLongLength 返回指示数组长度的 64 位整数。

不保证会对 Array 进行排序。在执行需要对 Array 进行排序的操作(如 BinarySearch)之前,必须对 Array 进行排序。

示例

下面的代码示例说明 Array.Copy 如何在 integer 类型的数组和 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

线程安全

此类型的公共静态(在 Visual Basic 中为 Shared)成员是线程安全的。但不能保证任何实例成员是线程安全的。

此实现不提供 Array 的同步(线程安全)包装;但是,基于 Array 的 .NET Framework 类使用 SyncRoot 属性提供它们自己的集合同步版本。

通过集合枚举在本质上不是一个线程安全的过程。即使一个集合已进行同步,其他线程仍可以修改该集合,这将导致枚举数引发异常。若要在枚举过程中保证线程安全,可以在整个枚举过程中锁定集合,或者捕捉由于其他线程进行的更改而引发的异常。

平台

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

其他资源

在数组中执行不区分区域性的字符串操作