System.Array.SetValue 方法 (Object, Int64[])

方法描述

将某值设置给多维 Array 中指定位置的元素。 索引指定为一个 64 位整数数组。

语法定义(C# System.Array.SetValue 方法 (Object, Int64[]) 的用法)

[ComVisibleAttribute(false)]
public void SetValue(
	Object value,
	params long[] indices
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
value System-Object 指定元素的新值。
indices System-Int64[] 64 位整数的一维数组,它表示用于指定要设置的元素的位置的索引。
返回值 void

提示和注释

indices 中的元素数必须等于 Array 中的维数。 indices 数组中的所有元素必须集体指定多维 Array 中所需元素的位置。

GetLowerBound 和 GetUpperBound 方法可确定 indices 数组中是否有任何值超出界限。

有关转换的更多信息,请参见 Convert。

此方法的运算复杂度是 O(1)。

注意

如果使用 SetValue 给值类型数组的元素赋值 null,则该元素的所有字段都初始化为零。 元素的值不是 null 引用,因此无法通过搜索 null 引用找到。

System.Array.SetValue 方法 (Object, Int64[])例子

下面的代码示例阐释了如何设置和获取一维或多维数组中的特定值。

using System;

public class SamplesArray  {

   public static void Main()  {

      // Creates and initializes a one-dimensional array.
      String[] myArr1 = new String[5];

      // Sets the element at index 3.
      myArr1.SetValue( "three", 3 );
      Console.WriteLine( "[3]:   {0}", myArr1.GetValue( 3 ) );


      // Creates and initializes a two-dimensional array.
      String[,] myArr2 = new String[5,5];

      // Sets the element at index 1,3.
      myArr2.SetValue( "one-three", 1, 3 );
      Console.WriteLine( "[1,3]:   {0}", myArr2.GetValue( 1, 3 ) );


      // Creates and initializes a three-dimensional array.
      String[,,] myArr3 = new String[5,5,5];

      // Sets the element at index 1,2,3.
      myArr3.SetValue( "one-two-three", 1, 2, 3 );
      Console.WriteLine( "[1,2,3]:   {0}", myArr3.GetValue( 1, 2, 3 ) );


      // Creates and initializes a seven-dimensional array.
      String[,,,,,,] myArr7 = new String[5,5,5,5,5,5,5];

      // Sets the element at index 1,2,3,0,1,2,3.
      int[] myIndices = new int[7] { 1, 2, 3, 0, 1, 2, 3 };
      myArr7.SetValue( "one-two-three-zero-one-two-three", myIndices );
      Console.WriteLine( "[1,2,3,0,1,2,3]:   {0}", myArr7.GetValue( myIndices ) );

   }

}


/* 
This code produces the following output.

[3]:   three
[1,3]:   one-three
[1,2,3]:   one-two-three
[1,2,3,0,1,2,3]:   one-two-three-zero-one-two-three

*/

异常

异常 异常描述
ArgumentNullException indices 为 null。
ArgumentException 当前 Array 中的维数不等于 indices 中的元素数。
InvalidCastException value 不能强制转换为当前 Array 的元素类型。
ArgumentOutOfRangeException indices 中的任何元素都超出当前 Array 的对应维度的有效索引的范围。

命名空间

namespace: System

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

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0、1.1 .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 系统要求。