Generic-related knowledge

Source: Internet
Author: User

Since the last party to participate in the club, feel the need to summarize the use of generics, although the head is very careful, there is no need to write, but as learners, I like to do their own learning in the form of the article to show out, so there is a part of me. We can experiment with a simple example: Instantiate a ArrayList and a list<int>, then add members to it, and finally read out the first member and perform an addition operation.

ArrayList _list = new ArrayList ();

_list.            ADD (1);

_list.            ADD ("a");

int i = (int) _list[0] + 1;

list<int> _list2 = new list<int> ();

_list2. ADD (1);//correct 

int j = (int) _list2[0] + 1;                 

Disadvantages of ArrayList:

1: When dealing with value types, there is boxing, folding box operation, affecting performance. _list. ADD (1), boxing occurs.

2: When handling reference types, there is no boxing and folding operations, but type conversion operations are still required. Code _list. ADD ("a") does not occur boxing.

3: The type conversion of the program runtime may throw an exception. When running _list[1], because it is a string, there is an exception to cast to int.

Generic processing: Generics use a generic data type T instead of object, specifying the type of T when the class is instantiated, the CLR automatically compiles to local code, and the data type is secure.

Generics Benefits:

1: Type-safe. For example, if you instantiate a class of type int, you cannot handle data of type string. Above the _list2. ADD ("a"), it will be an error.

2: When handling value types, no boxing and folding boxes are required. The int j=i+1;i can be taken directly and does not require a folding box operation.

3: No type conversions, including value types and reference types.

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.