Recently I am reading a book "What You Must Know.Net". The book covers a lot of content and has gradually summarized and understood the scattered things learned on the C# and .Net platforms in the past. Write down some basic things here.
Let’s talk about polymorphism first:
1. Base class inheritance polymorphism
As mentioned in the book, the key to the polymorphism of base class inheritance is the design and implementation of the inheritance system. A simple column is mentioned in the book
Files myFile=new WORDFile();
();
myFile is a parent class Files variable that maintains a reference to the subclass WORDFile instance, and then calls a virtual method Open. The specific call is determined by the runtime rather than the compile time. From the perspective of design pattern, the base class inheritance polymorphism reflects an IS-A method. For example, WORDFile IS-A Files is reflected in this inheritance relationship.
2. Interface implementation polymorphism
Different from the inheritance method of base classes, this polymorphism forms an inheritance system through the method agreement of implementing interfaces, which has higher flexibility. From the perspective of design pattern, the interface implementation of polymorphism reflects a CAN-DO relationship. The file loader above can also be implemented in this way
IFileOpen myFile=new WORDFile();
();
Polymorphic operating mechanism:
From a technical implementation perspective, it is the dynamic binding mechanism of .NET that has achieved object-oriented polymorphic characteristics. Static binding can determine associations during the compilation period, which are generally implemented by method overloading; dynamic binding determines dynamic association overwriting methods by checking virtual method tables during the run period, which are generally implemented by inheritance and virtual methods.