Generic T

effect:

Generic type can be used to maximize code reuse, the type of security protection and improve performance. The most common use is to create a generic collection classes

1, performance; as List <object> and List <T> is added to a data type int List, List <object> packing operation is required, and List <T> not required, the direct use of type int.

2, the type of security;

3, eliminate the cast;

4, binary code reuse;

 

First, Generics:

Generic method: You can specify a group of related methods in a way of life

Generic classes : You can specify a set of related classes in a class of life

Similarly, it can be used for generic interfaces, struct, delegate

 

Generic method:

1 static void PrintArray( T[] inputArray)
2 {
3      foreach(T  t in inputArray)
4         Console.Write(t);
5 }
Generic method

 

Generic constraints

 1 static T Maximum<T>(T x,T y) where T:Iomparable<T> 2 { 3 ...... 4 } 

 

Generic class

 1     class Stack<T>:IComparable<T>
 2     {
 3         private T[] Element;
 4         public T Pop()
 5         {
 6             return Element[1];
 7         }
 8 
 9         public int CompareTo(T other)
10         {
11             throw new NotImplementedException();
12         }
13     }
Generic class

 

Second, generics and inheritance

1, the non-generic class may inherit from a generic class, for example, the object class is the base class for each generic base class or indirectly.

2, generic class can inherit from a generic class

3, non-generic class can be derived from the generic class.

 

 

 

Guess you like

Origin www.cnblogs.com/qiupiaohujie/p/11964149.html