遵循类型安全枚举模式,我创建了一个小型类型安全枚举类。首次调用主对话框时,在调用InitializeComponent之后,它会调用另一个类的构造函数,该构造函数尝试将其类变量之一设置为类型安全枚举类的静态实例之一。问题是所有这些实例(以及它看起来的类)都是空的,从而导致程序崩溃。
如何让程序首先构造该类及其所有实例?我有点困惑,因为我认为静态实例是在程序开始时创建的,那么为什么在这种情况下不这样做呢?
这是令我失望的代码的精简版本: 类型安全的枚举模式实现:
public sealed class Types
{
public static readonly Types INVALID = new Types(-1, "Invalid");
... (other static instances and other implementations of the type-safe enum pattern)
}
主对话框的初始化:
public dlgMain()
{
InitializeComponent();
m_OtherClass = new OtherClass();
...
}
OtherClass 的构造函数
public OtherClass()
{
m_eType = Types.INVALID; // Crash!! the entire type-safe enum class and its static members are null!
...
}
编辑:好的,这是问题所在,
public sealed class Types
{
public static readonly Types INVALID = new Types(-1, "Invalid");
... (other static instances)
private static Dictionary<string, Types> mappings = new Dictionary<string, Types>(6); // There are 6 static types
private Types(int val, string name)
{
m_value = value; m_name = name;
mappings[name] = this; // This was causing the error, mappings is null
}
}