In the past two days, I have read the extensive programming video on webcast and the first four sections on generics on msdn.
Generics are concepts added by C #2.0 and the Common Language Runtime Library (CLR. The so-called generic type is implemented in the same copy through the type parameterCodeOperation on multiple data types. The type parameter makes it possible to design the following classes and Methods: these classes and Methods delay the designation of one or more types until the client Code declares and instantiates the class or method. Generic programming is actually a programming paradigm. It uses "parameterized type" to type parameters, so that code can be reused more flexibly.
The most common use of generics is to create a collection class .. The. NET Framework class library contains several new generic collection classes in the system. Collections. Generic namespace.
The two biggest advantages of generics are the ability to eliminate forced conversion between types and general base types in the general process, as well as packing and unpacking operations, and the ability to perform type checks during compilation. During circular access to large sets, forced conversion, packing, and unpacking operations have obvious impact on performance. For example, the following two instances are created using the non-generic collection class arraylist to store data of the value type and reference type respectively.
System. Collections. arraylist list1 = new system. Collections. arraylist ();
List1.add (3 );
List1.add( 105 );
System. Collections. arraylist list2 = new system. Collections. arraylist (); L
Ist2.add ("it is raining in Redmond .");
List2.add ("it is snowing in the mountains .");
Although arraylist is a collection class that is very convenient to use and can be used to store any reference or value type without modification, this convenience requires a price. Any reference or value type added to the arraylist is implicitly forcibly converted to an object. If the item is of the value type, you must perform the packing operation when adding it to the list, and cancel the packing operation during retrieval. In addition, the type check during compilation is missing: Because arraylist forcibly converts all items to objects, the client code cannot be prevented from performing the following operations during compilation:
System. Collections. arraylist list = new system. Collections. arraylist ();
// Add an integer to the list.
List. Add (3 );
// Add a string to the list. This will compile, but may cause an error later.
List. Add ("it is raining in Redmond .");
Int T = 0;
// This causes an invalidcastexception to be returned.
Foreach (int x in List)
{T + = x ;}
The following two problems can be solved by Using Generics:
// The. NET Framework 2.0 way to create a list
List <int> list1 = new list <int> ();
// No boxing, no casting:
List1.add (3 );
List <string> list2 = new list <string> ();
List2.add ("it is raining in Redmond ");