About type Object:
A 1.object type can refer to any type of instance;
2.object types can store values of any type;
3. You can define parameters of type object;
4. You can use object as the return type.
But--there's a big problem with that.
1. Because the programmer does not remember the type of use and error, resulting in incompatible types;
2. The interoperability of value types and reference types, which is the boxed unboxing, decreases the performance of the system.
The generics proposed by c#2.0 are to avoid forced type conversions, reduce box unboxing to improve performance, and reduce errors.
The System.Collections.Generic namespace provides a generic version of many collection classes and interfaces.
Defined:
public class Genericlist<t>
{
The public void Add (T input)//t is formulated as a type parameter
Public T Add ()//t as return value
}
<T> T is a type parameter that acts as a placeholder and is replaced by a real type at compile time.
Use generics:
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>> ();
In the case of List1 the compiler generates the following methods:
public void Add (int input)
public int Add ()
Generic class with multiple type parameters:
public class class name <T,U>
Generic constraint:
Ensure that the parameters used by the generic class are types that provide a specific method.
public class genericlist<t> where T:iemployee
If the IEmployee interface contains a method, the compiler verifies that the type used to replace T must implement the IEmployee interface.
Generic method: Allows you to take a way to define a generic class
Define generic method static void swap<t> (ref T LHS, ref t RHS)
{T temp; temp = LHS; LHS = RHS; RHS = temp;}
Using generic methods
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 delegates