In the process of learning C #, some basic knowledge, such as data types, control structures, arrays, and so on, are similar to the previous languages, and can be understood, however, the concept of upward transformation was first encountered.
After learning about it, I will roughly understand it as follows:
An upward transformation is to transform a subclass into a parent class, and an object can be used as its own type.
Let's take a look at a piece of code:
Public class Animal {public virtual void Eat () {Console. WriteLine ("I am an Animal, I want to Eat! ") ;}} Public class Bird: Animal {public override void Eat () {Console. WriteLine (" I'm a Bird, I want to Eat! ") ;}} Class Test {static void Main (string [] args) {Animal animal = new Bird (); // converts animal. Eat ();}}
In the above example, we define an animal class (where there is a way to eat), birds inherit the animal class (override the methods to eat in the base class ), the animal in the main function is an Animal type object, but the running result is not what we expected, but shows "I am a bird, I want to eat! ".
For this example. When animal is declared, the animal type is Animal. However, animal points to an Animal subclass, that is, Bird.
Of course, if there is an upward transformation, there will be a downward transformation, of course, the opposite way, that is, converting the parent class into a subclass.
When I see a problem on the Internet, some people say, "If the functions required by the subclass exist in the parent class, use the upward transformation. If the features required by the parent class exist in the subclass, "downward transformation is used," but as described above, Bird is a subclass of Animal. Bird has inherited the methods in Animal. Why do we need to use downward transformation? That is, why should we use "Animal = new Bird ();" instead of "Bird animal = new Bird ();" when defining animal?
Ask your friends to give us some comments and suggestions.