AboutObjectType:
1. The object type can be used to reference any type of instances;
2. The object type can store any type of value;
3. Parameters of the object type can be defined;
4. You can use the object as the return type.
But there is a big problem in doing so.
1. BecauseProgramThe member does not remember the type used and the error occurs, resulting in type incompatibility;
2. Mutual binning of value type and reference type reduces system performance.
In C #2.0, the generic type is proposed to avoid forced type conversion, reduce packing and unpacking, and improve performance and reduce errors.
The system. Collections. Generic namespace provides generic versions of many collection classes and interfaces.
Definition:
Public class genericlist <t>
{
Public void add (T input) // T is set as a type parameter
Public t add () // T is set to return value
}
<T> T is a type parameter, which acts as a placeholder,Replaced by real types during compilation.
Use generic:
Genericlist <int> list1 = new genericlist <int> ();
Genericlist <string> list2 = new genericlist <string> ();
Genericlist <Class Name> list3 = new genericlist <Class Name> ();
Genericlist <class name <int> list4 = new genericlist <class name <int> ();
Using list1 as an example, the compiler generates the following methods:
Public void add (INT input)
Public int add ()
Generic classes with multiple type parameters:
Public class name <t, u>
Generic constraints:
Make sure that the parameters used by generic classes are the types that provide specific methods.
Public class genericlist <t> where T: iemployee
If the iemployee Interface contains the method, the compiler will verify that the type used to replace T must implement the iemployee interface.
Generic method: This method can be used to define generic classes.
// Define the generic Method
Static void swap <t> (ref t LHS, ref t RHs)
{T temp; temp = LHS; LHS = RHS; RHS = temp ;}
// Use the generic Method
Public static void testswap () {int A = 1, B = 3;
Swap <int> (Ref A, ref B );
String S1 = "hello", S2 = "world ";
Swap <string> (ref S1, ref S2 );}
There are generic classes, generic interfaces, generic methods, generic delegation