我有一个抽象类,并希望为错误代码添加静态字典。我尝试了以下方法:
public abstract class Base
{
...
protected static readonly Dictionary<int, string> errorDescriptions = new Dictionary<int, string>()
{
{ 1, "Description1"},
{ 2, "Description2"},
...
};
...
}
然后发现这是在.NET 3.0中实现的;我正在使用2.0。我环顾四周,其他一些人建议我在构造函数中添加对,但这是一个抽象类。
我如何/应该填写字典?
感谢。
答案 0 :(得分:7)
public abstract class Base
{
...
protected static readonly Dictionary<int, string> errorDescriptions;
// Type constructor called when Type is first accessed.
// This is called before any Static members are called or instances are constructed.
static Base ()
{
errorDescriptions = new Dictionary<int, string>();
errorDescriptions[1] = "Description1";
errorDescriptions[2] = "Description2";
}
}