The maximum four benefits of generics are as follows:
1. Performance
Analyze the following example
The add () method of arraylist is defined as an object as a parameter. Therefore, an integer type must be boxed. When reading values in the arraylist, You need to unpack and convert the object to the integer type. Packing and unpacking are easy to use, but the performance loss is relatively high, especially when many items are iterated.
Code 1: arraylist list = new arraylist (); list. add (44); // boxing-covert a value type to a reference typeint I1 = (INT) list [0] // unboxing-covert a reference type to a value typeforeach (INT I2 in list) {console. writeline (I2); // unboxing}
The list <t> class does not use objects, but defines the type during use. In the following example, the generic type of the List <t> class is defined as int, so the int type is used in the dynamically generated class by the JIT compiler, and no packing or unpacking operations are performed.
Code2: List <int> List = new list <int> (); list. add (44); // No boxing-value types are stored in the list <int> int I1 = list [0]; // No unboxing, no cast neededforeach (INT I2 in list) {console. writeline (I2 );}
2. type security
It is easy to understand, that is, if the type does not match, an error is returned. Ensure type security
3. BinaryCodeReuse
Generics allow better reuse of binary code. Generic classes can be defined at a time and instantiated with many different types. You do not need to accessSource code.
4. Code Extension
I don't understand what it means.