How to solve the arraylist. copyto () running error in C #

Source: Internet
Author: User
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);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.