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.