Stressed: static Constructors (C # programming guide)

Source: Internet
Author: User

A static constructor is used to initialize any
Static data, or to perform a participates action that needs has med once only. It is called automatically before the first instance is created or any static members are referenced.

 
ClassSimpleclass {// Static ConstructorStaticSimpleclass (){//...}}

Static constructors have the following properties:

    • A static constructor does not take access modifiers or have parameters.

    • A static constructor is called automatically to initialize
      Class before the first instance is created or any static members are referenced.

    • A static constructor cannot be called directly.

    • The user has no control on when the static constructor is executed in the program.

    • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.

    • Static constructors are also useful when creating Wrapper Classes for unmanaged code, when the constructor can callLoadlibraryMethod.

Example

In this example, the classBusHas a static constructor and one static member,Drive (). When
Drive ()Is called, the static constructor is invoked to initialize the class.

  Public   class  bus { // static constructor:   static  bus () {system. console. writeline ( "the static constructor invoked. ") ;}< span style =" color: Blue "> Public   static   void  drive () {system. console. writeline ( "the drive method invoked. ") ;}}< span style =" color: Blue "> class  testbus { static   void  main () {bus. drive () ;}< SPAN class = "lw_collapsiblearea_title"> output 

   

the static constructor invoked.

the drive method invoked.

Ref:

http://msdn.microsoft.com/en-us/library/k9x6w0hc (vs.80 ). aspx

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.