? One of the reasons for generics is to solve the boxing and unpacking problems of elements in the original collection class:
First, the generic type:
/// <summary> ///return to foreground message/// </summary> /// <typeparam name= "T" ></typeparam> Public classYzt_message<t> { Private intM_request_type =1; //return to foreground success error type: 1: Success (default) 0: Error Public intRequest_type {Get{returnM_request_type;} Set{M_request_type =value;} } Private stringM_request_message ="Current Error"; //back to reception information Request_type = = 0 o'clock, the current error data will not be taken Public stringRequest_message {Get{returnM_request_message;} Set{m_request_message =value;} } //information to return to the foreground, possibly a JSON object PublicT Request_object {Get;Set; } //return to foreground information, possibly a collection of JSON objects PublicIlist<t> Request_list {Get;Set; } }
When called: if T is of type string:
yzt_message<string> pMessage = new yzt_message<string> ();
try{
Pmessage.request_object = "OK";
Pmessage.request_type = 1;
}
catch (Exception err) {
Pmessage.request_type = 0;
Pmessage.request_message = Err. Message;
}
Second, generic method:
Public classDemo {//This is a generic method that can be used in a normal class Public Static voidSwap<t> (refT LHS,refT RHS) {T temp; Temp=LHS; LHS=RHS; RHS=temp; } //To invoke a generic method: Public Static voidTestswap () {intA =1; intb =2; Swap<int> (refArefb);//The type parameter can also be omitted, and the compiler infers the parameter. Swap (ref a, ref B);System.Console.WriteLine (A +" "+b); } }
Three, generic interface
Public class Demo { publicinterface iface<t> { T sayhi (); void SayHello (T msg); } }
To implement a generic interface:
Mode one: Common class implements generic interface:
Public class interfacedemo2:webapplication1.interfacedemo.iface<string> { public string Sayhi () { thrownew notimplementedexception (); } Public void SayHello (string msg) { thrownew NotImplementedException (); } }
Mode two: generic class, implement generic interface, so more flexible
Public class Interfacedemo<t>:webapplication1.interfacedemo.iface<t> { public T Sayhi () { thrownew notimplementedexception (); } Public void SayHello (T msg) { thrownew notimplementedexception (); } }
Custom generic classes, generic methods, and generic interfaces in C #