Before you begin to explain Arraylist.copyto () in C # to run the wrong solution, let's look at a piece of code:
The following is a reference fragment:
ArrayList list = new ArrayList();
list.Add(1);
list.Add(2);
byte[] buf = new byte[2];
list.CopyTo(buf);
This code looks good normal, compile also very smoothly, but the implementation of the error, why?
Anatomical ArrayList, whose interior is implemented with an object array, as a container for all elements, the value type must be converted to a reference type to store, otherwise no 2.0 generic appears. The CopyTo function is implemented with array.copy (), and the problem is with it. When we add constant values to the list, such as list. ADD (1), where 1 is considered to be int,box stored in the object and then unbox back int, and then become high-precision to the low precision copy int[]->byte[], there is an error, the equivalent of the following code:
The following is a reference fragment:
int[] a1 = new int[2]{1,2};
byte[] a2 = new byte[2];
Array.Copy( a1, a2, 2 );
Back to the original code to modify is also very simple, as long as the box before it into a small precision type can be, the modified code is as follows:
The following is a reference fragment:
ArrayList list = new ArrayList();
list.Add((byte)1);
list.Add((byte)2);
byte[] buf = new byte[2];
list.CopyTo(buf);