Generics defer the determination of the type of a class or method until the class or method is instantiated, that is, the first declaration is not specifying a type, and then specifying the type when it is used (instantiated)
Generics can be used for classes, methods, delegates, events, and so on
Let's write a simple generic type
Public class Genericclass<t>{ void somemethod ( t t ) { // do something }}
Here's how to use it:
Instantiate a class
?
1 |
GenericClass< int > gci= new GenericClass< int >(); |
Method SomeMethod has an integer-type parameter.
Write an example below
usingSystem;usingSystem.Collections.Generic;usingSystem.Text;namespaceexample{classGenericclass<t> { Public voidPrinttype (T t) {Console.WriteLine ("value:{0} type:{1}", T,t.gettype ()); } } classProgram {Static voidMain (string[] args) { inti =0; Genericclass<int> GCI =Newgenericclass<int>(); Gci. Printtype (i); strings ="Hello"; Genericclass<string> GCS =Newgenericclass<string>(); Gcs. Printtype (s); Console.ReadLine (); } }}
a generic method can appear on a generic or non-generic type. It is important to note that the method is a generic method, not as long as the method belongs to a generic type, or even if the type of the method's formal parameter is a generic parameter of the enclosing type. A method can be called a generic method only if it has its own type parameter list. In the following code, only method G is a generic method.
?
1 2 3 4 5 6 7 8 |
class A { T G<T>(T arg) {...} } class Generic<T> { T M(T arg) {...} } |
Where of generics
The where of generics can be qualified for type parameters. There are several ways to do this.
The where t:struct restriction type parameter T must inherit from System.ValueType.
The where T:class restriction type parameter T must be a reference type, that is, cannot inherit from System.ValueType.
where t:new () restriction type parameter T must have a default constructor
The where T:nameofclass restriction type parameter T must inherit from a class or implement an interface.
These limits can be combined, for example: public class point where T:class, IComparable, New ()
For example:
class person<t> where t:class {} " Span style= "Color:rgb (0, 0, 255); >class program { static void Main (string Span style= "Color:rgb (0, 0, 0); >[] (args) {person <int > bb = new person<// error 1 type "int" must be a reference type to be used as a parameter in the generic type or method "Consoleapplication1.person<t>" T " }}