C#中的Array.ConstrainedCopy()方法

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

语法

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("Array elements...");
      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]);
      }
   }
}

输出结果

这将产生以下输出-

Array elements...
20 50 100 150 200 300 400
Destination Array:
150 200 300 400 0 0 0 0 0 0