1. What is generic?
A:Generic is a type template and type is a template of an instance (object. C # provides five generic types: Class, interface, Delegate, structure, and method.
2. What are the advantages of using generics?
A: inheritance implements "code reuse ",Generic implementation is another form of code reuse, that is, "algorithm reuse ".To sum up, it has the following advantages:
1> improve code reusability.
2> type security during compilation. When an incompatible type is used, an error is reported during compilation, instead of waiting for the runtime to report an error, which improves type security.
3> better performance. When operating a value-type instance, the use of the generic type will reduce the value-type packing, so that the memory allocation on the hosting stack of the program is less, and garbage collection is not so frequent, this improves program performance.
Use generic instances
The following is an example of stack implementation using generics. The main method defines two variables, stackint and stackstring. Use int and string as the type parameters to create instances (objects) of the two construction types ). The Code is as follows:
Namespace genericdemo1 {// defines a generic class mystack <t> {T [] stackarray; // declares that the array references int stackpointer = 0; const int maxstack = 10; bool isstackfull // read-only attribute {get {return stackpointer> = maxstack ;}} bool isstackempty {get {return stackpointer <= 0 ;}} public void push (t x) // inbound stack {If (! Isstackfull) // stack below {stackarray [stackpointer ++] = x ;}} public t POP () // output stack {return (! Isstackempty )? Stackarray [-- stackpointer]: stackarray [0];} public mystack () // constructor {stackarray = new T [maxstack]; // instantiate an array object} public void print () {for (INT I = stackpointer-1; I> = 0; I --) {console. writeline ("value: {0}", stackarray [I]) ;}} class program {static void main (string [] ARGs) {var stackint = new mystack <int> (); // instantiate the construction type, equivalent to mystack <int> stackint = new mystack <int> (); vaR stackstring = new mystack <string> (); stackint. push (3); // call the push method. Note that the real parameter of the type is int stackint. push (5); stackint. push (7); stackint. print (); stackstring. push ("A"); // call the push method. Note that the real parameter of the type is string stackstring. push ("B"); stackstring. print (); console. readkey ();}}}
The program output result is: