C # Base Key understanding

Source: Internet
Author: User

The largest use place of the base is on the polymorphism of the polygon-relative development. (What is polymorphism, how to understand polymorphism)

Base can "finish" calling its base class constructor when creating an instance of a derived class or calling a method on a base class that has been overridden by another method

About base Call base class constructor (only one class constructor calls another class's constructor)

public Class A {public        a () {            Console.WriteLine ("Build a");        }    }    public class B:a {public        B (): Base ()        {            Console.WriteLine ("Build B");            }    }
Create an instance object of B, and get the result of both build a and build B.

Instantiate Class B
         Build//Further expand  Call the base class constructor's public  class BaseClass
{
int num;
Public BaseClass ()
{
Console.WriteLine ("In BaseClass ()");
}
public BaseClass (int i)
{
num = i;
Console.WriteLine ("In BaseClass (int {0})", num);
}
}
public class Derivedclass:baseclass
{
The constructor calls Baseclass.baseclass ()
Public DerivedClass ()
: Base ()
{
}
The constructor calls Baseclass.baseclass (int i)
Public derivedclass (int i)
: Base (i)
{
}
static void Main ()
{
DerivedClass dc = new DerivedClass ();
DerivedClass DC1 = new DerivedClass (1) ();
Console.ReadLine ();
}
}


A method that always calls a base class in a derived class (which is actually an override of a virtual method)

    public class Q {public        virtual void Hello () {            Console.WriteLine ("Hello");        }    }    public class W:q {public        override void Hello ()        {            base. Hello ();            Console.WriteLine ("World");        }    }
Instantiate class W
Output Hello World

  

C # Base Key understanding

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.