Is there any d开发者_运维百科ifference between Array.Copy
and CopyTo
? Are they just overloaded?
Same functionality, different calling conventions. Copy
is a static method, while CopyTo
isn't.
Array.Copy(arraySrc, arrayDest, arraySrc.length);
arraySrc.CopyTo(arrayDest, startingIndex);
Look at it carefully. Copy
is a static method whereas CopyTo
is an instance method.
But they are not only convention-wise different; there is a key functional difference.
Here is an excerpt from MSDN:
This method (
Array.CopyTo
) supports theSystem.Collections.ICollection
interface. If implementingSystem.Collections.ICollection
is not explicitly required, useCopy
to avoid an extra indirection.
Comparing
https://msdn.microsoft.com/en-us/library/k4yx47a1.aspx and
https://msdn.microsoft.com/en-us/library/06x742cw.aspx,
We will see that:
Array.CopyTo
- able to copy multidimensional arrays.
- easier to specify range to be copied.
- static method.
CopyTo
- have better performance. (as husayt answered)
- instance method.
And there are something I am not sure that, the remarks of Array.CopyTo
said:
This method is equivalent to the standard C/C++ function
memmove
, notmemcpy
.
Which CopyTo
do not have such description.
It is true that it is not easy to copy part of an array to it self using CopyTo
without parameters to control range. Still, you could use ArraySegment
or array.Skip(offset).Take(length)
to achieve it.
And in my test, there is no problem to do so.
Functionally, I don't know if there is anything different between the two other than the CopyTo method will copy all elements of the array and Copy will allow you to specify a range of elements to copy
精彩评论