There are several ways to copy array in C #
Replication between arrays, int[] pins = {9,3,4,9};int [] alias = pins; There is an error and the source of the error, the above code is not a mistake, but it is not a copy at all, because pins and alias are references, exist on the stack, and data 9, 3,4,3 is an int object that exists in the heap, int [] alias = pins; just create another reference, alias and pins point to {9,3,4,3} at the same time, and when one of the references is modified, it is bound to affect the other. Copying means creating a new object that is identical to the object being copied, which should be replicated in the C # language in the following 4 ways.
Method One: Use a For loop
int []pins = {9,3,7,2}
int []copy = new Int[pins.length];
for (int i =0;i!=copy.length;i++)
{
Copy[i] = pins[i];
}
Method Two: Use the CopyTo () method in the Array object
int []pins = {9,3,7,2}
int []copy2 = new Int[pins.length];
Pins. CopyTo (copy2,0);
Method Three: Use a static method of the array class copy ()
int []pins = {9,3,7,2}
int []copy3 = new Int[pins.length];
Array.copy (pins,copy3,copy. Length);
Method four: Using one of the instance methods in the array class, Clone (), can be called one time, the most convenient, but the Clone () method returns an object, so cast to the appropriate class type.
int []pins = {9,3,7,2}
int []COPY4 = (int []) pins. Clone ();
Method Five:
String[] Student1 = {"$", "$", "C", "M", "D", "1", "2", "3", "1", "2", "3"};
String[] Student2 = {"0", "1", "2", "3", "4", "5", "6", "6", "1", "8", "16", "10", "45", "37", "82"};
ArrayList student = new ArrayList ();
foreach (string s1 in Student1)
{
Student. ADD (S1);
}
foreach (String s2 in Student2)
{
Student. ADD (S2);
}
String[] Copyafter = (string[]) student. ToArray (typeof (String));
Two arrays merge, and finally assign the merged result to the Copyafter array, this example can be flexible, many places can use