Article Source: Tianji Forum
Before explaining how to solve the arraylist. copyto () running error in C #, let's take a look.Code:
The following is a reference clip:
Arraylist list = new arraylist ();
List. Add (1 );
List. Add (2 );
Byte [] Buf = new byte [2];
List. copyto (BUF );
This Code seems to be normal, and compilation is successful, but an error occurs during execution. Why?
Anatomy of arraylist, which is implemented using an object array. as a container for all elements, the value type must be converted to the reference type for storage. Otherwise, 2.0 of generic is not required. The copyto function is implemented using array. Copy () internally, and the problem lies in it. When we add a constant value to the List, such as list. add (1), where 1 is regarded as int, and box is stored in the object and then Unbox is returned to int, as a result, the int []-> byte [] is copied with high precision to low precision, and an error occurs, which is equivalent to the following code:
The following is a reference clip:
Int [] a1 = new int [2] {1, 2 };
Byte [] a2 = new byte [2];
Array. Copy (A1, A2, 2 );
Looking back, the original code is easy to modify, as long as it is converted into a small precision type before box, the modified Code is as follows:
The following is a reference clip:
arraylist list = new arraylist ();
list. add (byte) 1);
list. add (byte) 2);
byte [] Buf = new byte [2];
list. copyto (BUF);