本文介绍了静态变量初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
今天,我与同事进行了讨论,并总结了以下几点.如果一切正确或需要修改,请稍加说明.
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.-3.您无法确切知道它何时发生,因此不能依赖它.静态构造函数可以让您稍微控制一下在调用它时会发生什么.
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.静态构造函数很慢
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 classexecutes before any instance of theclass is created.
- The static constructor for a classexecutes before any of the staticmembers for the class are
referenced. - The static constructor for a classexecutes after the static field initializers (if any) for the class.
- The static constructor for a classexecutes, at most, one time duringa single program instantiation.
- The order of execution between twostatic constructors of two
different classes is not specified.
这篇关于静态变量初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!