什么时候静态变量获得在C#中初始化? [英] When do static variables get initialized in C#?
问题描述
我想知道什么时候一个静态变量(一类)进入画面(初始化)?它被称为是第一次或类加载后的实例构造后?
什么时候一个类装载发生的?
I was wondering about when does a static variable(in a class) come into picture(initialized)? Is it after the instance constructor called for the first time or after the class loads? When does a class loading occur?
推荐答案
哦,这是复杂的。这取决于 beforefieldinit
标志是否被设置,这反过来又(在C#)取决于是否有一个静态构造函数。更糟糕的是;在.NET 4中的我相信的行为改变,使其更加偷懒比它曾经是。
Oh, that is complex. It depends on whether the beforefieldinit
flag is set, which in turn (in C#) depends on whether there is a static constructor. And worse; in .NET 4 I believe the behaviour changed to make it more "lazy" than it used to be.
坦率地说,我不会code到这里的任何特定的行为;简单:您尝试使用它们,只要使用普通的code来访问他们之前的静态字段将被初始化
Frankly, I wouldn't code to any specific behaviour here; simply: static fields will be initialized before you try to use them, as long as you use regular code to access them.
乔恩斯基特对这里和<一本一个很好的写了href=\"http://blogs.msmvps.com/jonskeet/2010/01/26/type-initialization-changes-in-net-4-0/\">here
这篇关于什么时候静态变量获得在C#中初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!