When static variable is allocated i.e. when 开发者_如何学Goyou declare class or at the time of object creation?
It is compiled into the static constructor. So the first time anyone creates an object of the class or calls a static method or property on it, the initialization occurs.
Edit: when it is important to you if initialization happens before of after your own static constructor code (and some other edge cases),check the link in the comment by divo.
the first time the class is accessed....
As other answers have indicated, this will happen in the type (static) constuctor. If your class does not have a type constructor explicitly defined then the compiler will generate one for you. However, determining exactly when this constructor is called is a bit more involved.
If your class does not define an explicit type constructor, e.g.
public class Foo
{
public static int Bar = 1;
}
then the C# compiler will generate a constructor and emit the class definition with the beforefieldinit
flag. This will cause the JIT compiler to guarantee that the type constructor is called sometime before a member of the type is first used but this time is non-deterministic, i.e. it is not possible to know exactly when this will happen, and it could be at a much earlier point than when a type member is first used.
If your class declares an explicit type constructor, e.g.
public class Foo
{
public static int Bar;
static Foo()
{
Bar = 1;
}
}
then the compiler will emit IL for the class without the beforefieldinit
flag. In this case the JIT compiler will call the type constructor at a deterministic time, i.e. immediately before the first type member access.
The former JIT behaviour is known as before-field-init semantics and the latter as precise sematntics. It is important to know the difference between the two since, in some scenarios, they may have a significant performance implication.
Static variables are allocated as soon as static (type) constructor is called. This happens when you call any method that reference the type for the first time, before method execution.
精彩评论