Home > Article > Backend Development > Several methods of copying arrays in C#
I suddenly learned it, so I put it on my blog to share it, just think of it as a learning diary.
First of all, let me explain that the array is a reference type, so be careful not to copy the address but not the value when copying!
In fact, when copying an array, you must use new to open up a new space in the heap specifically for storing the array, so that it is effective.
(1)
int[] pins = { 9, 3, 7, 2 }; int[] copy=new int[pins.length]; for (int i = 0; i < copy.length; i++) { copy[i] = pins[i]; }
(2)
int[] copy = new int[pins.Length]; pins.CopyTo(copy, 0);
(3)
Int[] pins= new int[4]{9,3,7,2}; Int[] alias=pins;
Note that this kind of copy is just a reference, it just passes the address of the data to the alias array, so it is not recommended to copy the array in this way;
(4)
Array.Copy(pins,copy,copy.Length)
(5)
Int[] copy=(int[])pins.Clone();
Here is why the forced type conversion of int[] is used. The reason is that the result type of Clone is object. So it needs to be cast to int[]
The Object class is actually the base class of all our classes.
The above several methods (summary) of copying arrays in C# are all the content shared by the editor. I hope it can give you a reference, and I hope you will support the PHP Chinese website.
For more C# related articles on several methods of copying arrays, please pay attention to the PHP Chinese website!