System.Array.CreateInstance 方法 (Type, Int32)

方法描述

创建使用从零开始的索引、具有指定 Type 和长度的一维 Array。

语法定义(C# System.Array.CreateInstance 方法 (Type, Int32) 的用法)

public static Array CreateInstance(
	Type elementType,
	int length
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
elementType System-Type 要创建的 Array 的 Type。
length System-Int32 要创建的 Array 的大小。
返回值 System.Array 使用从零开始的索引、具有指定 Type 和指定长度的新的一维 Array。

提示和注释

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

将引用类型元素初始化为 null。 将值类型元素初始化为零。

此方法的运算复杂度为 O(n),其中 n 是 length。

System.Array.CreateInstance 方法 (Type, Int32)例子

下面的代码示例说明如何创建和初始化一维 Array。

using System;
public class SamplesArray  {

   public static void Main()  {

      // Creates and initializes a one-dimensional Array of type Int32.
      Array my1DArray=Array.CreateInstance( typeof(Int32), 5 );
      for ( int i = my1DArray.GetLowerBound(0); i <= my1DArray.GetUpperBound(0); i++ )
         my1DArray.SetValue( i+1, i );

      // Displays the values of the Array.
      Console.WriteLine( "The one-dimensional Array contains the following values:" );
      PrintValues( my1DArray );
   }


   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 one-dimensional Array contains the following values:
    1    2    3    4    5
*/

异常

异常 异常描述
ArgumentNullException elementType 为 null。
ArgumentException elementType 不是有效的 Type。
NotSupportedException
  • 不支持 elementType。 例如,不支持 Void。
  • elementType 是一个开放式泛型类型。
ArgumentOutOfRangeException length 小于零。

命名空间

namespace: System

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0、1.1、1.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1 受以下版本支持:

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。