Differential analysis of polymorphism overloading and rewriting in C

  • 2020-11-03 22:33:45
  • OfStack

This article summarizes the concepts and differences between polymorphism, overloading and overwriting in C#. Good reference for beginners of C#. Share to everybody for everybody reference. The specific analysis is as follows:

Overriding: means overriding methods in a base class, where methods must have the modifier virtual, and subclass methods must specify override.

Format as follows:

1. In base class:


public virtual void myMethod() 
{ 
} 

2. In subclasses:


public override void myMethod() 
{ 
} 

After the override, the myMethod() method is accessed using both the base class object and the subclass object. The result is that the method redefined in the subclass is accessed and the base class method is overridden.

Overload: Used to select the best function member to invoke given a list of arguments and a set of candidate function members.


public void test(int x,int y){} 

public void test(int x,ref int y){} 

public void test(int x,int y,string a){} 

Features of heavy load:

I. Method names must be the same

II. The argument list must be different, regardless of the order of the argument list

III. The return value type can be different

But if there are generics, pay attention!

Polymorphism: The polymorphism of c# is mainly reflected in the inheritance of classes:

When a child inherits a superclass, it might have the same name but a different method definition,
So in the subclass, the original method will be overridden to implement its own requirements.

There are two points to note:

Methods 1 that can be overridden in subclasses must be marked as virtual(virtual), abstract (abstract), override(overridden) the functions marked as virtual and abstract are created for the purpose of overrides, the function marked as override itself is overridden by the first two functions, so it is natural that it can be overridden;

The overridden function must appear in a subclass, and any function of a superclass can only be overridden once in a subclass. This makes sense because when you override twice, the subclass will define two functions with the same return type, method name and argument list, which is definitely not possible.

I believe that this article has a certain reference value for the learning of C# programming.


Related articles: