Workaround for Arraylist.copyto () run errors in C #

Source: Internet
Author: User

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);

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.