c basic learning polymorphism

  • 2020-05-19 05:36:57
  • OfStack

Recently, I read a book "what you must know.Net", which covers a lot of content. I have gradually summarized and gained a new understanding of the scattered things I learned in the past on the platform of c# and.Net. Put some basic stuff down here.

Let's talk about polymorphism first:

1. Inherited polymorphism of base class

As mentioned in the book, the key to the inheritance polymorphism of the base class is the design and implementation of the inheritance system. A simple example is given in the book


      Files myFile=new WORDFile();
      myFile.open();

myFile is a parent Files variable that holds a reference to a subclass WORDFile instance, and then calls a virtual method Open, depending on the runtime and not the compile time. From the perspective of design pattern, the inherited polymorphism of base class embodies one IS-A mode, such as WORDFile IS-A Files, which is embodied in this inheritance relationship.

2. Interface implementation polymorphism

Different from the inheritance method of base class, this polymorphism forms the inheritance system through the method convention of implementing interface, which has higher flexibility. From the perspective of design patterns, interface implementation polymorphism embodies an CAN-DO relationship. The above file loader can also be implemented in this way


      IFileOpen myFile=new WORDFile();
      myFile.open();

The operation mechanism of polymorphism:

From a technical implementation point of view, it is the dynamic binding mechanism of.NET that contributes to the object-oriented polymorphism. Static binding can be determined at compile time, 1 is usually implemented by method overloading; Dynamic binding determines the method of dynamic association overwrite by checking the virtual method table at run time, which is generally implemented by inheritance and virtual methods.


Related articles: