Static constructors and field initialization order

    Static field initializers run just beforethe static constructor is called. If a type has no
static constructor, field initializers will execute just prior to the type being used—
or anytime earlierat the whim of the runtime. (This means that the presence of a
static constructor may cause field initializers to execute later in the program than
they would otherwise.)
Static field initializers run in the order in which the fields are declared. The following
example illustrates this: Xis initialized to 0 and Yis initialized to 3.

1 class Foo
2 {
3 public static int X = Y; // 0
4 public static int Y = 3; // 3
5 }

If we swap the two field initializers around, both fields are initialized to 3. The next
example prints 0 followed by 3 because the field initializer that instantiates a  Foo
executes before Xis initialized to 3:

 1 class Program
 2 {
 3 static void Main() { Console.WriteLine (Foo.X); } // 3
 4 }
 5 class Foo
 6 {
 7 public static Foo Instance = new Foo();
 8 public static int X = 3;
 9 Foo() { Console.WriteLine (X); } // 0
10 }

If we swap the two lines in boldface, the example prints 3 followed by 3.

 

转载于:https://www.cnblogs.com/ifutan/archive/2013/06/06/Static-constructors-and-field-initialization-order.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值