gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 20:53:06 27 4
gpt4 key购买 nike

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com