The Generic Model delays the determination of the class or method type to instantiate the class or method, that is, the type is not specified at the beginning of the Declaration, and the type is specified when the class or method is to be used (instantiated ).
Generics can be used for classes, methods, delegates, events, etc.
Next, write a simple generic
Public class genericclass <t>
{
Void somemethod (T)
{
// Do something
}
}
The usage is as follows:
Instantiate a class
Genericclass <int> GCI = new genericclass <int> (); The somemethod method has an integer type parameter.
The following is an example.
Using system;
Using system. Collections. Generic;
Using system. text;
Namespace example
{
Class genericclass <t>
{
Public void printtype (T)
{
Console. writeline ("value: {0} type: {1}", T, T. GetType ());
}
}
Class Program
{
Static void main (string [] ARGs)
{
Int I = 0;
Genericclass <int> GCI = new genericclass <int> ();
GCI. printtype (I );
String S = "hello ";
Genericclass <string> GCS = new genericclass <string> ();
GCS. printtype (s );
Console. Readline ();
}
}
}
Generic methods can appear on generic or non-generic types. It should be noted that the method is not a generic method as long as the method belongs to the generic type, or even the type of the form parameter of the method is a closed type generic parameter. A method can be called a generic method only when the method has its own list of type parameters. In the following code, there are only methodsGIs a generic method.
Class
{
T g <t> (T Arg ){...}
}
Class generic <t>
{
T m (t Arg ){...}
}
Generic where
Generic where can limit the type parameters. The following methods are available.
· Where T: struct restriction type parameter T must inherit from system. valuetype.
· Where T: Class restriction type parameter T must be a reference type, that is, it cannot inherit from system. valuetype.
· Where T: New () restriction type parameter T must have a default constructor
· Where T: nameofclass restriction type parameter T must inherit from a class or implement an interface.
These limits can be used in combination, such as: public class point where T: Class, icomparable, new ()
For example:
Class person <t> where T: Class
{
}
Class Program
{
Static void main (string [] ARGs)
{
Person <int> BB = new person <int> (); // contains multiple,
Error 1 type "int" must be of the reference type to be used as the parameter "T" in the generic type or method "leleapplication1.person <t>"
}
}