Static variables, static constructor, instance variables, and constructor execution.

Source: Internet
Author: User

 

See the following code. The input result is as follows:

 

The first output and the second output are both quite understandable. Why is the third output (Why are all static variables and static constructors not executed )?

 

Let's discuss it!

 

 

 

Static void Main (string [] args)

{

Console. WriteLine ("BaseA basea = new BaseA ();");

BaseA basea = new BaseA ();

Basea. MyFun ();

Console. WriteLine ();

 

Console. WriteLine ("BaseB baseb = new BaseB ();");

BaseB baseb = new BaseB ();

Baseb. MyFun ();

Console. WriteLine ();

 

Console. WriteLine ("BaseA basec = new BaseB ();");

BaseA basec = new BaseB ();

Basec. MyFun ();

Console. WriteLine ();

}

 

 

Public class BaseA

{

Public static MyTest a1 = new MyTest ("base class static variable ");

Public MyTest a2 = new MyTest ("base class instance variable ");

Static BaseA ()

{

MyTest a3 = new MyTest ("base class static constructor ");

}

Public BaseA ()

{

MyTest a4 = new MyTest ("base class instance constructor ");

}

Public virtual void MyFun ()

{

MyTest a5 = new MyTest ("base class instance function MyFun ");

}

}

Public class BaseB: BaseA

{

Public static MyTest b1 = new MyTest ("derived static variable ");

Public MyTest b2 = new MyTest ("derived instance variable ");

Static BaseB ()

{

MyTest b3 = new MyTest ("derived static constructor ");

}

Public BaseB ()

{

MyTest b4 = new MyTest ("derived instance constructor ");

}

Public new void MyFun ()

{

MyTest b5 = new MyTest ("derived instance function MyFun ");

}

}

Public class MyTest

{

Public MyTest (string info)

{

Console. WriteLine (info );

}

}

 

Author taoliuhua

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.