C # Proverbs: initializing static members with static constructors

Source: Internet
Author: User
Tags constructor exception handling execution tostring
function | It is unavoidable to use static members when writing programs statically, because the access of static members is detached from the type object, so it is unreasonable to use non-static constructors, private methods, or some other methods. NET provides member initialization statements and static constructors to initialize static members.

Based on the previous unit, we can know that the initialization statements for static members are performed earlier than the static constructor, followed by the benefits and limitations of the member initialization statements. One thing to mention here is the difference between a static constructor and an instance constructor, because a static constructor is executed by a CLR call, so a static constructor can only be a single and cannot have parameters. Then there are some drawbacks to the static constructors in relation to the member initialization.

In addition, the biggest problem with member initialization is that the exception cannot be captured, and it may be possible for ordinary members to add Try-catch when constructing type objects, and for static members, it is sometimes not possible to determine which type of access statement is executed first. Adding Try-catch to each use type reduces the readability of the program. But if this anomaly is emitted, it can cause the entire program to crash. Then using the static constructor can better catch the exception, and do exception handling.

A comparison of static member initialization statements and static constructors is generally as follows.

Simplicity of Security Exception handling
Static member initialization Most convenient More secure Very difficult
Static constructors Relatively simple Most secure Easy

So what exactly is the way to initialize static members, give the following two points of advice:

The first is the simple static member, for example, the type is a value type, and so on, using the member initialization statement to complete;

If the second static member initialization is more complex, or if there is a possibility of an exception, it is done with a static constructor.

The content of this unit is basically finished, now say static member The most important one application "Singleton", is to guarantee this type of object uniqueness. In fact, the implementation is very simple, the following is a simple example.

public class Mysingleton
{
private static readonly Mysingleton _theoneandonly;
Static Mysingleton ()
{
_theoneandonly = new Mysingleton ();
}
public static Mysingleton Theonly
{
get{return _theoneandonly;}
}

<summary>
Private constructor to avoid object created from outside
</summary>

Private Mysingleton ()
{}
}
When a static member is initialized, it is possible to look closely at the object construction steps that I mentioned in the previous unit. may seem abstract, especially when analyzing nested relationships, now give an example to illustrate.

Class A
{
public static int X = B.Y;
Static A ()
{
++x;
}
}

Class B
{
public static int Y = a.x;
Static B ()
{
++y;
}
}
So let's guess what the following call output is.

Debug.WriteLine (A.x.tostring ());
Debug.WriteLine (B.y.tostring ());
The result is "2,1", that is, the a.x value is 2, and the B.Y value is 1.

To analyze this kind of problem, just remember three o ' line.
  
First code execution sequence, the code before the first execution;

The second static member initialization statement is executed before the static constructor;

The third static member initialization statement and the static constructor are executed only once.

If you understand these three points, then you will analyze why the results above are present.

When the first statement is invoked,

Debug.WriteLine (A.x.tostring ());
The first is to access the type A, then initialize the static member of this type, and then, if there is a static constructor, you need to call it.

For a static member only "X", according to the process of the previous unit, first allocate space to it, supplemented by 0来 initialization, and then call its corresponding member initialization statement to initialize this static member.

Then its member initialization statement is "x = B.y", so it is necessary to access "B.Y" to initialize the static member of X.

Access to "B.Y" is the access to type B, which is also the same as accessing a, initializes the static member of this type first, and then, if there is a static constructor, it needs to be invoked. and B's static member only "Y", first assigns the space, and is supplemented by the 0来 initialization, then calls its corresponding member initialization statement to initialize this static member.

For the "Y = a.x" Member initialization statement, the call to static member initialization and static constructors is no longer performed because the first access to type A is not at this time, and access to "a.x" is direct. At this point, the value of "a.x" is 0, the value of Y is also 0, and then the static constructor of B is executed, so that the value of Y is 1.

So the member initialization statement "X = B.y" In A is done, at which point the X in type A is the same as Y in type B, with a value of 1. However, both static member initialization statements and static constructors in B have been executed, and the static constructors in a are not yet executed. So after the static constructor of a, the x value of a is 2, which is the result of the final display.

The analysis process looks very round, in fact, as long as you grasp the three principles I said earlier, then in the same complex problem analysis

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.