C# 数组 - ConstrainedCopy() 方法

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

此方法保证如果复制未完全成功,则所有更改都将被撤消。

异常

ConstrainedCopy()方法有以下异常 -

  • ArgumentNullException:如果sourceArray和destinationArray之一为null,则抛出此异常。
  • RankException:如果数组的维数不同,则抛出此异常。
  • ArrayTypeMismatchException:如果sourceArray的类型与destinationArray不兼容,则抛出此异常。
  • InvalidCastException:如果sourceArray中的元素无法转换为destinationArray的类型,则抛出此异常。
  • ArgumentOutOfRangeException:如果源索引、目标索引或长度超出范围,则抛出。
  • ArgumentException 如果要复制的范围无效,则抛出。

语法

以下是 C# 数组 ConstrainedCopy() 方法的语法 -

public static void ConstrainedCopy (Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length);

参数

此方法接受以下参数 -

  • sourceArray:包含要复制数据的数组。
  • sourceIndex:一个 32 位整数,表示 sourceArray 中开始复制的索引。
  • destinationArray:接收数据的数组。
  • destinationIndex:一个 32 位整数,表示 destinationArray 中开始存储的索引。
  • length:要复制的元素数量。

返回值

此方法不会返回任何修改目标数组的值。

示例 1:基本示例

让我们创建一个基本示例,说明如何使用C# 代码中的 ConstrainedCopy() 方法 −

using System;
class Program
{
   public static void Main()
   {
      int[] source = { 1, 2, 3, 4, 5 };
      int[] destination = { 10, 20, 30, 40, 50 };

      Array.ConstrainedCopy(source, 1, destination, 2, 2);
      Console.WriteLine(string.Join(", ", destination));
   }
}

输出

以下是输出 -

10, 20, 2, 3, 50

示例 2:处理引用类型

让我们看另一个 ConstrainedCopy() 方法的示例。源对象的前两个元素从索引 1 开始复制到目标对象中 -

using System;
class Program
{
   public static void Main()
   {
      string[] source = { "apple", "banana", "cherry" };
      string[] destination = { "orange", "grape", "kiwi" };

      Array.ConstrainedCopy(source, 0, destination, 1, 2);

      Console.WriteLine(string.Join(", ", destination));
   }
}

输出

以下是输出 -

orange, apple, banana

示例 3:异常安全

在此示例中,我们使用 ConstrainedCopy() 来实现异常安全。即使发生异常,由于 ConstrainedCopy 的原子行为,目标数组仍保持不变 -

using System;
class Program
{
   public static void Main()
   {
      int[] source = { 1, 2, 3, 4, 5 };
      int[] destination = { 10, 20, 30, 40, 50 };

      try {
         Array.ConstrainedCopy(source, 3, destination, 4, 3); 
      } catch (Exception ex) {
         Console.WriteLine($"Error: {ex.Message}");
      }
      Console.WriteLine(string.Join(", ", destination));
   }
}

输出

以下是输出 -

Error: length
10, 20, 30, 40, 50

示例 4:ArrayTypeMismatchException 异常

在本例中,我们使用 ConstrainedCopy() 方法检查源类型和目标类型是否相同。如果不同,则抛出 ArrayTypeMismatchException 异常 -

using System;
class Program
{
   public static void Main()
   {
      object[] source = { "Hello", 123, "World" };
      string[] destination = new string[3];

      try {
         Array.ConstrainedCopy(source, 0, destination, 0, 3);
      } catch (ArrayTypeMismatchException ex) {
         Console.WriteLine($"Error: {ex.Message}");
      }
   }
}

输出

以下是输出 -

ERROR!
Unhandled Exception:
System.InvalidCastException

csharp_array_class.html