Method rewriting:
The base class method identifies the virtual keyword, and the method rewriting in the subclass (inherited class) identifies the override keyword.
The overridden method must have the same type as the base class, such as method name, return and accepted parameters.
public class Class1 { public virtual void show(int i) {……} } public class Class2:Class1 { public override void show(int a) {……} }
New method rewriting:
public class Class1 { protected virtual void show(int i) {……} } public class Class2:Class1 { public new int show(int a) {……} }
The new statement defines its own method of the same name. The return type and access type can be different from the method with the same name of the base class.
If the accepted parameters are different from those of the base class method with the same name, the new keyword will be redundant, which is equivalent to general rewriting (the base class does not have the same method or the same hidden method).
override rewrites the method body of the base class method (hidden method), and new rewrites the base class method with the same name (receiving the same parameters).
Terminate inheritance:
Terminate inheritance identification sealed. The following code compiles error, Class2 cannot inherit the closed class Class1
public sealed class Class1 { public virtual void show(int i) {……} } //public class Class2:Class1 //{ // public override void show(int a) // {……} //}
Call the base class constructor:
The compiler first calls the base class constructor, and then calls the inherited class constructor.
public class Class1 { public Class1(int i , string j) {……} } public class Class2:Class1 { public Class2(int i,string j,object obj):base(i,j) {……} }
The above is the little knowledge of C# (4): inheritance content. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!