1. Generic class
Defined:
Class Test<t> Note: T is placeholder can be written casually
{
public T data; Note: Define a field of type T
Public Test (t obj) Note: Defines a method of type T
{
This.data = obj;
}
}
Instantiating a generic class
private static void Main (string[] args)
{
test<int> test = new test<int> (3);
Console.WriteLine (Test.data);
Console.readkey ();
}
2. Generic methods
Defined:
public static void swap<t> (Ref t A, ref T B) value: Defines a generic method, ref refers to whether the reference return value is stored as a reference for the caller to be modified by the local
{
A = b;
}
private static void Main (string[] args)
{
int a = 1;
int b = 2;
swap<int> (ref a, ref B); Note: Pass two values of type int
Console.Write (a);
Console.readkey ();
}
3. Generic constraints
public static void swap<t> (Ref t A, ref T B) where t:struct Note: Delivery type must be a value type
{
A = b;
}
public static void swap<t> (Ref t A, ref T B) where T:class Note: The delivery type must be a reference type
{
A = b;
}
public static void swap<t> (Ref t A, ref T B) where t:new () Note: The pass-type parameter must have a common constructor with no parameters. When used with other constraints, thenew () constraint must be specified last.
{
A = b;
}
public static void swap<t> (Ref t A, ref T B) where t:< base class name > Note: The pass-type parameter must be the specified base class or derived from the specified base class.
{
A = b;
}
public static void swap<t> (Ref t A, ref T B) where t:< interface name > Note: The pass-type parameter must be the specified interface or implementation of the specified interface. You can specify multiple interface constraints. The constraint interface can also be generic.
{
A = b;
}
public static void swap<t> (Ref t A, ref T B) where T:u Note: The type parameter provided for T must be a parameter supplied for u or a parameter derived from U. This is called a bare type constraint.
{
A = b;
}
c#2.0 generics