C# 中的 Array.ConstrainedCopy() 方法

csharpprogrammingserver side programming更新于 2025/9/20 10:30:00

C# 中的 Array.ConstrainedCopy() 方法用于从指定的源索引开始复制数组中的一系列元素,并将它们粘贴到从指定的目标索引开始的另一个数组中。

语法

public static void ConstrainedCopy (Array sourceArr, int sourceIndex, Array destinationArr, int destinationIndex, int length);

这里,

  • sourceArr − 包含要复制的数据的数组。

  • sourceIndex − 一个 32 位整数,表示 sourceArr 中复制开始的索引。

  • destinationArr −接收数据的数组。

  • destinationIndex − 一个 32 位整数,表示 destinationArr 中存储开始的索引。

  • len − 一个 32 位整数,表示要复制的元素数量。

现在让我们看一个实现 Array.ConstrainedCopy() 方法的示例 −

示例

using System;
public class Demo{
   public static void Main(){
      int[] arrDest = new int[10];
      Console.WriteLine("数组元素...");
      int[] arrSrc = { 20, 50, 100, 150, 200, 300, 400};
      for (int i = 0; i < arrSrc.Length; i++){
         Console.Write("{0} ", arrSrc[i]);
      }
      Console.WriteLine();
      Array.ConstrainedCopy(arrSrc, 3, arrDest, 0, 4);
      Console.WriteLine("Destination Array: ");
      for (int i = 0; i < arrDest.Length; i++){
         Console.Write("{0} ", arrDest[i]);
      }
   }
}

输出

这将产生以下输出 −

数组元素...
20 50 100 150 200 300 400
Destination Array:
150 200 300 400 0 0 0 0 0 0

相关文章