Advantages and disadvantages of generics:
Performance
Type Security
Binary code reuse
Code Extension
Naming Conventions (letter T as the prefix)
Create a generic type as follows:
public class LinkedListNode<T>{ public LinkedListNode(T value) { this.Value = value; } public T Value{get;private set;} public LinkedListNode<T> Next{get;internal set;} public LinkedListNode<T> Prev{get;internal set;}}public class LinkedList<T>:IEnumerable<T>{ public LinkedListNode<T> First{get;private set;} public LinkedListNode<T> Last{get;private set;} public LinkedListNode<T> AddLast(T node) { var newNode = new LinkedListNode(node); if(First == null) { First = newNode; newNode.Prev = Last; Last = First; } else { LinklistNode previous = Last; Last.Next = newNode; Last = newNode; Last.Prev = previous; } return newNode; } public IEnumerator<T> GetEnumerator() { LinkedListNode<T> current = First; while(current != null) { yield return current.Value; current = current.Next; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }}
Functions of generic classes
In a generic type, generic default is used to initialize a generic type to null or 0 based on whether the generic type is a reference type or a value type.
Generics support several constraints:
Where T: struct for structural constraints, type T must be a value type
Where T: Class class constraints the specified type T must be a reference type
Where T: ifoo the specified type T must implement the interface ifoo
Where T: New () is a constructor constraint. A default constructor is required for the specified type T.
Where t1: the T2 constraint can also be specified. Type T1 is derived from generic Type T2. This constraint is also called a bare type constraint.
You can also combine multiple constraints using generic types.
Static members of a generic class can only be shared in one instance of the class.
Generic Interface
Generic Structure
Nullable <t>
Structure nullable <t> defines a constraint: the generic type T must be a structure
As follows:
public struct Nullable<T> where T:struct{ public Nullable(T value) { this.hasValue = true; this.value = value; } private bool hasValue; public bool HasValue; { get { return hasValue; } } private T value; public T Value; { get { if(!hasValue) { throw new InvalidOperationException("no value"); } return value; } } public static explicit operator T(Nullable<T> value) { return value.Value; } public static implicit operator Nullable<T>(T value) { return new Nullable<T>(value); } public override string ToString() { if (!HasValue) return String.Empty; return this.value.ToString(); }}
Define a variable of the null type and use "?"
Generic Method
C # Study Notes ---- generic