在静态类中声明一个Dictionary

Gra*_*ton 87 .net c# dictionary

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

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

但是编译器抱怨" 除了字符串之外的引用类型的const字段只能用null初始化 ".

Yon*_*ona 207

如果要声明字典一次并且从不更改它,则将其声明为readonly:

private static readonly Dictionary<string, string> ErrorCodes
    = new Dictionary<string, string>
{
    { "1", "Error One" },
    { "2", "Error Two" }
};
Run Code Online (Sandbox Code Playgroud)

如果您希望字典项是只读的(不仅是引用而且是集合中的项),那么您将不得不创建一个实现IDictionary的只读字典类.

查看ReadOnlyCollection以供参考.

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


Gra*_*ton 8

正确的语法(在VS 2008 SP1中测试)是这样的:

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


are*_*ing 5

老问题,但我发现这很有用。事实证明,字典还有一个专门的类,使用字符串作为键和值:

private static readonly StringDictionary SegmentSyntaxErrorCodes = new StringDictionary
{
    { "1", "Unrecognized segment ID" },
    { "2", "Unexpected segment" }
};
Run Code Online (Sandbox Code Playgroud)

编辑:根据下面克里斯的评论,通常首选使用Dictionary<string, string>over StringDictionary,但这取决于您的情况。如果您正在处理较旧的代码库,您可能会仅限于StringDictionary. 另请注意以下行:

myDict["foo"]
Run Code Online (Sandbox Code Playgroud)

myDict如果是 a则返回 null StringDictionary,但如果是 则抛出异常Dictionary<string, string>。有关更多信息,请参阅他提到的 SO 帖子,这是此编辑的来源。

  • [为什么要使用 `StringDictionary` 而不是 `Dictionary&lt;string, string&gt;`?](http://stackoverflow.com/questions/627716/stringdictionary-vs-dictionarystring-string) (2认同)