在静态类中声明一个字典 [英] Declare a Dictionary inside a static class

查看:1241
本文介绍了在静态类中声明一个字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在静态类中声明静态字典对象?我试过

How to declare a static dictionary object inside a static class? I tried

public static class ErrorCode
{
    public const IDictionary<string, string> ErrorCodeDic = new Dictionary<string, string>()
    {
        { "1", "User name or password problem" }     
    };
}

但编译器抱怨说引用类型的const字段除了字符串之外,只能用null 来初始化。

But the compiler complains that "A const field of a reference type other than string can only be initialized with null".

推荐答案

如果您要声明一次字典,永远不要更改,然后将其声明为只读方式:

If you want to declare the dictionary once and never change it then declare it as readonly:

private static readonly Dictionary<string, string> ErrorCodes
    = new Dictionary<string, string>
{
    { "1", "Error One" },
    { "2", "Error Two" }
};

如果要将字典项目只读(不仅仅是引用,也是集合中的项目) )然后您将不得不创建一个实现IDictionary的只读字典类。

If you want to dictionary items to be readonly (not just the reference but also the items in the collection) then you will have to create a readonly dictionary class that implements IDictionary.

查看ReadOnlyCollection作为参考。

Check out ReadOnlyCollection for reference.

BTW const只能在内联声明标量值时使用。

BTW const can only be used when declaring scalar values inline.

这篇关于在静态类中声明一个字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆