C # static constructor in details

Source: Internet
Author: User
Static constructor, which is rarely used in East China.
Static constructor is still interesting. It has the following characteristics:
1) The static constructor is executed before the constructor is executed.
2) When a static member of the call class is called, the static constructor is executed first.
3) The static constructor is executed only once. (No matter whether you create an object or call a static member of the class)
The following are classes that contain static constructors. Public   Class Test
{
Private   Static   String _ Name;

Public Static StringName
{
Get{Return_ Name ;}
Set{_ Name=Value ;}
}

StaticTest ()
{
Console. writeline ("Static Constructor");
}

PublicTest (StringName)
{
_ Name=Name;
}

Public test ()
{< br> console. writeline ( " constructor " );
}

Public Static VoidMethod ()
{
Console. writeline ("Static Functions");
}
}

Test 1:
Class stater
{
Static void main ()
{
Test test = new test ();
Console. readkey ();
}
}
Result:

Test 2:
Class stater
{
Static void main ()
{
Testing. Name = "123 ";
Test. Method ();
Console. readkey ();
}
}
Result:

Test 3:
Class stater
{
Static void main ()
{
Test test = new test ();
Test Test2 = new test ("landpy ");
Test test3 = new test ();
Test. Method ();
Test. Name = "landpy ";
Console. readkey ();
}
}
Result:

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.