Do both of these constructors do the same?

Do both of these blocks of code the same way?

class A {
   public static int s;
   A(){}
   static A(){s = 100;}
}

and

class A {
   public static int s=100;
   A(){}
   //static A(){s = 100;} do not use
}

Do they do the same? I think so.

+4
source share
4 answers

No, they do not behave quite like that. Without a static constructor, the timing of when the type initializer is executed is much weaker - this can happen sooner or later than you expected.

When there is a static constructor, the type initializer is executed when the type is first used in terms of any static member being accessed, or any instantiated instance.

, , - ( ). JIT , (, , ) ( , , ).

IL , beforefieldinit; .

+11

, . , . , .

, , - (, ).

+4

, beforefieldinit, , . , IL . beforefieldinit .

class A
{
    public static int s;
    A() { }
    static A() { s = 100; }
}

class B
{
    public static int s = 100;
    B() { }
}

...

.class private auto ansi A
    extends [mscorlib]System.Object

.class private auto ansi beforefieldinit B
    extends [mscorlib]System.Object

/.

+3

# , - static ( appconfig.config). Init , .

0

All Articles