Home > Backend Development > C#.Net Tutorial > C# Supplementary Knowledge (4): Inheritance

C# Supplementary Knowledge (4): Inheritance

黄舟
Release: 2017-02-07 15:17:08
Original
1386 people have browsed it

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)
        {……}
    }
Copy after login

New method rewriting:

    public class Class1
    {
        protected virtual void show(int i)
        {……}
    }
    public class Class2:Class1
    {
        public new int show(int a)
        {……}
    }
Copy after login

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)
    //    {……}
    //}
Copy after login

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)
        {……}
    }
Copy after login

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)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template