【问题标题】:C# Static Dictionary Declare and Initialize in Abstract Class .NET 2.0C# 静态字典在抽象类 .NET 2.0 中声明和初始化
【发布时间】:2011-10-12 15:23:27
【问题描述】:

我有一个抽象类,想为错误代码添加一个静态字典。我尝试了以下方法:

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# dictionary abstract-class


    【解决方案1】:
    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";
       }
    }
    

    【讨论】:

    • 谢谢,只是几个后续问题。所以如果派生类DerivedClass使用字典DerivedClass.errorSescriptions,程序首先调用Base()?还是仅在创建派生类时使用public DerivedClass(,,) : base() {...}?构造函数是静态的有什么原因吗?
    • 一个单独的字典被创建并且可供所有子类使用。是的,它是在使用任何子类之前实例化的。
    • 如果Base有其他非静态字段,构造函数不应该是静态的吗?
    • @Jon 你可以在同一个类中拥有一个静态 ctor 和多个实例 ctor。
    • errorDescriptions[1] = "Description1";给出一个错误,你应该使用 errorDescriptions.Add(1, "Description1");
    猜你喜欢
    • 1970-01-01
    • 2013-03-30
    • 1970-01-01
    • 1970-01-01
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    • 2011-08-26
    • 2010-11-19
    相关资源
    最近更新 更多