Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

c# - static variables initialization

Today I had a discussion with my colleague and concluded following points. Kindly throw some light if all are correct or some modification is required.

  1. When static constructor is not defined in class, static fields are initialized just before their use.
  2. When static constructor is defined in class, static fields are initialized just before their use or as part of (before) instance creation.
  3. If no static field is accessed within a static method and that static method is called. the static fields will be initialized only if static constructor is defined in that class.
  4. If possible static constructor should be avoided in a class.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

1.-3.You cannot exactly know when it happens and so you cannot depend on it. A static constructor will give you a little control what happens when it get called.

public class UtilityClass
{
  //
  // Resources
  //

  // r1 will be initialized by the static constructor
  static Resource1 r1 = null;

  // r2 will be initialized first, as static constructors are 
  // invoked after the static variables are initialized
  static Resource2 r2 = new Resource2();

  static UtilityClass()
  {
    r1 = new Resource1();
  }

  static void f1(){}
  static void f2(){}
}

4.Static constructors are slow

The exact timing of static constructor execution is implementation-dependent, but is subject to the following rules:

  • The static constructor for a class executes before any instance of the class is created.
  • The static constructor for a class executes before any of the static members for the class are
    referenced.
  • The static constructor for a class executes after the static field initializers (if any) for the class.
  • The static constructor for a class executes, at most, one time during a single program instantiation.
  • The order of execution between two static constructors of two
    different classes is not specified.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...