Static field/property initialization
If I have a type like this:
public struct Effect
{
public int Value { get; set; }
public static int MinValue 开发者_开发问答= Int32.MinValue;
}
Would MinValue
be initialized only ONCE, just like the execution of a static constructor? Or should I initialize MinValue
inside a static constructor?
Would this be any different for classes
?
Yes, it would initialize exactly once, before static constructor execution. Same for reference types (classes).
Yes, it will be initialized only once per process (app domain).
It will be executed exactly once, but not quite as if it were in a static constructor. The rules about when type initializers are executed are different when a type has a static constructor. Note that the observed behaviour changed a bit in .NET 4.0, too. Usually you don't need to worry about that though.
As far as I'm aware, there's no difference in type initialization between classes and structs.
Note that your MinValue
field is public and writable - is it meant to be? That seems like a bad idea.
精彩评论