Understanding of static Constructor

Source: Internet
Author: User
I saw a question two days ago ~~ Class Program
{
Static   Void Main ( String [] ARGs)
{
Caculator ca =   New Caculator ();
Caculator CA1 =   New Caculator ();
Console. writeline ( " Current object count is: "   + Caculator. instancecount. tostring ());
Console. Readline ();
}
}

Public   Class Caculator
{
Public   Static   Int Instancecount;
Static Caculator ()
{
Instancecount++;
}
Public Caculator ()
{
Instancecount++;
}
}

What is the output result ~~~

It should be 3, why ~~~? To understand this problem, you must first know when static functions will be called ~~, In. net. the static constructor cannot be called directly. Therefore, the public constructor is called during the instantiation operation. this question is a little different '~

For example, add a public parameter before the static caculator () method. As mentioned earlier, the static constructor cannot be called directly. Therefore, the public modifier is invalid, compilation fails. at the same time, this method cannot contain parameters (or because it cannot be manually called), otherwise it is also invalid.

So what is the use of this static constructor ~~ For example, you can use it to initialize the log class ~~ ApplicationProgramYou can use it to write logs.

It can also be used as a packaging class for unmanaged resources. Here you can call the loadlibrary method to select the version to be loaded.

 

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.