C# 中的 Stack.CopyTo() 方法

2024 年 8 月 29 日 | 4 分钟阅读

C# 中的 CopyTo() 方法允许您将元素从一个数组复制到另一个数组或数组中的特定位置。它提供了一种方便的方法来复制数组的内容,并确保目标数组在指定范围内包含相同的值。通过指定目标数组和起始索引,您可以轻松控制元素复制过程,并促进高效的数据和数组操作。

语法

它具有以下语法:

参数

  1. 数组:这是一个一维数组,是堆栈中复制元素的目的地。数组必须具有基于零的索引。
  2. arrIndex:这是数组中复制开始的基于 0 的索引。

Exception

  1. ArgumentNullException:如果数组为 null。
  2. ArgumentOutOfRangeException:如果索引小于 0。
  3. ArgumentException:如果数组是多维的,或者源堆栈中的元素数量大于从索引到目标数组末尾的可用空间。
  4. InvalidCastException:如果源堆栈类型无法自动转换为目标数组类型。

示例 1

让我们举一个例子来说明如何在 C# 中实现 stack.CopyTo() 方法。

输出

The elements of the Stack are:
2501
2002
1520
1245
1100
750
560
320
115
The total elements of the stack = 9
Element 750 is the stack? = True
The Updated Stack elements are
3050
2501
2002
1520
1245
1100
750
560
320
115
Count of elements (updated) = 10
Is 5050 is present in the stack? = False
The cloned stack elements
3050
2501
2002
1520
1245
1100
750
560
320
115
The updated count of the stack elements = 10
The cloned elements are copied into the integer array
3050
2501
2002
1520
1245
1100
750
560
320
115

示例 2

让我们举一个例子来说明如何在 C# 中实现 stack.CopyTo() 方法。

输出

The elements of the stack are......
Science
Maths
English
Hindi
Telugu
The total count of elements= 5
Is Maths is the stack? = True
The updated.. elements of the stack are
Physics
Science
Maths
English
Hindi
Telugu
Count of elements (updated) = 6
Is the Physics element is in stack? = True
The cloned.. stack elements are
Physics
Science
Maths
English
Hindi
Telugu
The count of the updated stack = 6
The elements are cloned and copied in the string array.
Physics
Science
Maths
English
Hindi
Telugu

Stack.CopyTo() 方法的优点

C# 中的 Stack.CopyTo() 方法有几个优点。一些主要优点如下:

  • 高效的集群初始化

如果您需要将 Stack 的内容复制到集群中,CopyTo() 方法可能比手动从 Stack 中删除内容并将其分配给集群更有效。它提供了一种简洁明了的方法来实现这一点。

  • 堆栈排列容量

CopyTo() 策略在复制集群时保留了 Stack 中元素的顺序。它确保维护结果集群中组件的排列,这在某些情况下可能是必要的。

  • 扩展实际计划

该策略可以指定目标集群中的起始索引,从而允许您灵活地管理复制操作。您可以控制组件在集群中的复制位置。

  • 与集群的兼容性

由于 CopyTo() 策略是 C# 中组织集群的一种方式,因此它与常见的编程习惯非常吻合。如果您使用集群并需要从 Stack 导入组件,那么使用此策略是一种熟悉且一致的策略。