c# - 当 CopyTo 非静态方法的目标和源是同一个数组时,如何可能发生重叠?

标签 c# arrays

Programming C# 5书,我读过:

As well as the static Copy method, the Array class defines a nonstatic CopyTo method, which copies the entire array into a target array, starting at the specified offset. This method is present because all arrays implement certain collection interfaces, including ICollection (where T is the array’s element type), which defines this CopyTo method. Copy To does not guarantee to handle overlap correctly, and the documen tation recommends using Array.Copy in scenarios where you know you will be dealing with arrays—CopyTo is just for the benefit of general purpose code that can work with any implementation of a collection interface.



它表示使用 CopyTo 时无法正确处理重叠非静态方法。问题是我认为没有当我们使用 CopyTo 时可能会发生重叠在阵列上!因为,它试图复制 整个 数组到目的地。如果目标与源相同,则目标与源大小相同,因此,我们可以复制到的唯一位置是 0 (我的意思是第二个参数必须为零:myArray.CopyTo(myArray, 0)),因此,每个元素都被精确地复制到它已经存在的索引处。那么这本书所说的重叠问题是什么?
我所说的都可以在下面的代码中看到:
> var a = new int[] { 1, 2, 3 };
> a
int[3] { 1, 2, 3 }
> a.CopyTo(a, 0) // this is the only way I can call this method without 
                 // getting error, If I want to pass the same array as first argument
> a
int[3] { 1, 2, 3 }  // nothing went wrong! What is to worry about?

除了我所说的之外,为什么有人可以在索引 0 处将数组复制到自身中?这样做有什么意义?我错过了什么?

请注意,这与 this SO post 不是同一个问题。 .那个 SO 帖子是关于 Copy方法,而不是 CopyTo .
我认为在处理数组时所有关于重叠的考虑,只有当我们将数组传递给 Copy() 时才有意义。 .如该SO帖子中所述。

最佳答案

CopyTo调用归结为对 Array.Copy 的调用在 array.cs .所以是的,这与 that SO post 相同.

关于c# - 当 CopyTo 非静态方法的目标和源是同一个数组时,如何可能发生重叠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61992912/

相关文章:

php - 如何通过 php 对 mongodb 上的嵌套对象进行排序?

c# - 为什么文本框中的自动完成 jquery 在内容占位符中使用时不起作用?

c# - 使用 C# 将多个文档插入 Mongodb 的最快方法

c# - 同一命名空间中的类和扩展方法容器类。有什么好处?

arrays - 索引匹配不同日期和值之间的搜索

javascript - Eloquent Javascript 第 4 章 : arrayToList/listToArray Execise

c# - 当前进程没有线程?

c# - .NET EF 6 复数形式,表名称中带有前缀

c++ - 整数数组求和的分治算法

javascript - 循环遍历Array并且只接收特定数据