Polymorphism means that the same object has different behaviors in different scenarios, that is, executing different code. Of course, this different scenario refers to the actual object that the class Pointer Points to, then the actual object method is called.
There are three methods for implementing polymorphism in C # language.
1. Override the virtual method of the parent class,
2 interface inheritance
3. abstract class inheritance
If you can understand the example below, you have made great progress. The following section only describes the polymorphism by rewriting the virtual method of the parent class.
Using system; using system. data; using system. text; Class programe {Public Delegate void mydelgatemath (); static void main (string [] Arg) {try {baseclass tempfath; baseclass fathobj = new baseclass (); fathobj. say (); sonclass sonobj = new sonclass (); sonobj. say (); son2class son2obj = new son2class (); son2obj. say (); tempfath = sonobj; tempfath. say (); tempfath = son2obj; tempfath. say (); console. writeline ("The above is learning, below is the actual example of polymorphism, and the Application Scenario"); baseclass [] famliys = new baseclass [3] {fathobj, sonobj, son2obj }; foreach (baseclass o in famliys) {o. say () ;}} catch (exception ERR) {console. writeline (err. message) ;}} public class baseclass {public baseclass () {console. writeline ("My name am [" + this. tostring () + "] When I was born, I don't want my son to be an asshole. Don't say anything about him. ");} Virtual public void say () {console. writeline ("") ;}} public sealed class sonclass: baseclass {public sonclass () {} override public void say () {console. writeline ("son spoke") ;}} public sealed class son2class: baseclass {public son2class () {}override public void say () {console. writeline ("two sons spoke ");}}}
Copy the above Code to the CS file. The running result is as follows:
---------- Run ---------- ==================== run C # program write by cicnor ====================== my name am [programe + baseclass] When I was born, I don't want my son to be a follower, don't say anything about him. Lao Tzu spoke my name am [programe + sonclass] When I was born, I don't want my son to be a follower. Don't say anything about him. My son spoke my name am [programe + son2class] When I was born, I don't want my son to be a follower. Don't say anything to me. The second son spoke. The above is learning. The following is an example of polymorphism, in addition, in the Application Scenario, I spoke to my son, and my son spoke to me =============== the program ended copy cicnor 2001 ========== ========= output completed (0 sec consumed) -Normal termination