How statics are initialized in C#
Ok, I have greatly changed the code to show the actual problem more clearly. I have tested this code, and it definitely fails.
public class MyEnumBase
{
private int _val;
private开发者_Python百科 static Dictionary<int, MyEnumBase> ValueMap = new Dictionary<int, MyEnumBase>();
protected MyEnumBase()
{
_val = ValueMap.Count;
ValueMap.Add(_val, this);
}
public static MyEnumBase ValueOf(int i)
{
return ValueMap[i];
}
public static IEnumerable<MyEnumBase> Values { get { return ValueMap.Values; } }
public override string ToString()
{
return string.Format("MyEnum({0})", _val);
}
}
public class Colors : MyEnumBase
{
public static readonly Colors Red = new Colors();
public static readonly Colors Green = new Colors();
public static readonly Colors Blue = new Colors();
public static readonly Colors Yellow = new Colors();
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("color value of 1 is " + Colors.ValueOf(2));
}
}
The following code fails because the Colors constructor is never called before ValueOf() is called. Is there a clean way to ensure that all my static fields are called before I call ValueOf?
Thanks, ~S
Static fields get initialized before you use them. Exact time depends on implementation and you should not make any assumptions about it. Static fields initialization:
The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration. If a static constructor (Section 10.11) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor. Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class.
The code that you posted should work:
Child.TimesConstructed()
will not print 0 if you access one of the children (Child.C1
) prior to this call.
精彩评论