C# 静态字典在抽象类 .NET 2.0 中声明和初始化

发布于 2024-12-09 11:42:41 字数 406 浏览 1 评论 0原文

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

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

但后来发现这是在.NET 3.0中实现的;我用的是2.0。我环顾四周,其他一些人建议我在构造函数中添加对,但这是一个抽象类。

我如何/应该填充字典?

谢谢。

I have an abstract class and would like to add a static dictionary for error codes. I tried the following:

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

but then discovered that this was implemented in .NET 3.0; I am using 2.0. I looked around and some others suggested I add the pairs in the constructor but this is an abstract class.

How can/should I populate the dictionary?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

倾`听者〃 2024-12-16 11:42:41
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";
   }
}
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";
   }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文