在Type-Safe枚举模式之后,我创建了一个小型的安全枚举类.首次调用主对话框时,在调用InitializeComponent之后,它会调用另一个类的构造函数,该类尝试将其中一个类变量设置为类型安全枚举类的静态实例之一.问题是所有这些实例(以及它看起来的类)都是null,从而导致程序崩溃.
如何让程序首先构造该类及其所有实例?我有点困惑,因为我认为静态实例是在程序开始时创建的,那么为什么在这种情况下不能这样做呢?
这是我失败的代码的浓缩版本: 类型安全的枚举模式实现:
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)
}
Run Code Online (Sandbox Code Playgroud)
主对话框的初始化:
public dlgMain()
{
InitializeComponent();
m_OtherClass = new OtherClass();
...
}
Run Code Online (Sandbox Code Playgroud)
OtherClass的构造函数
public OtherClass()
{
m_eType = Types.INVALID; // Crash!! the entire type-safe enum class and its static members are null!
...
}
Run Code Online (Sandbox Code Playgroud)
编辑:好的,这是问题,
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
}
}
Run Code Online (Sandbox Code Playgroud)
如何让程序首先构造该类及其所有实例?我有点困惑,因为我认为静态实例是在程序开始时创建的,
事实并非如此.在第一次使用包含静态数据的类型之前的某个时刻创建静态数据.这通常在"使用"值之前初始化,但不是在程序启动时初始化.(但在这种情况下应该没关系.)
那么为什么在这种情况下不这样做呢?
它实际上可能正是这样做的.问题更可能在你的构造函数中Types.当静态构造函数运行时,它需要初始化每个readonly实例Types.如果构造函数期望已经初始化静态数据或其他类似问题,则可能导致抛出异常.
我建议在Types构造函数中放置一个断点(以及用于初始化静态数据的任何其他构造函数).这通常有助于诊断和发现真正的问题.