c#静态字典的声明和初始化.net 2.0中的抽象类

本文关键字:抽象类 net 静态 字典 声明 初始化 | 更新日期: 2023-09-27 18:11:09

我有一个抽象类,并希望为错误代码添加一个静态字典。我尝试了以下操作:

public abstract class Base
{
   ...
   protected static readonly Dictionary<int, string> errorDescriptions = new Dictionary<int, string>()
   {
      { 1, "Description1"},
      { 2, "Description2"},
      ...
    };
   ...
}

,但后来发现这是在。net 3.0中实现的;我用的是2.0。我四处看了看,其他人建议我在构造函数中添加对,但这是一个抽象类。

我怎样才能/应该填充字典?

谢谢。

c#静态字典的声明和初始化.net 2.0中的抽象类

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";
   }
}