Declare a Dictionary inside a static class

后端 未结 9 1219
無奈伤痛
無奈伤痛 2020-12-23 11:11

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

public static class ErrorCode
{
    public const IDictionary E         


        
9条回答
  •  情深已故
    2020-12-23 11:42

    Old question, but I found this useful. Turns out, there's also a specialized class for a Dictionary using a string for both the key and the value:

    private static readonly StringDictionary SegmentSyntaxErrorCodes = new StringDictionary
    {
        { "1", "Unrecognized segment ID" },
        { "2", "Unexpected segment" }
    };
    

    Edit: Per Chris's comment below, using Dictionary over StringDictionary is generally preferred but will depend on your situation. If you're dealing with an older code base, you might be limited to the StringDictionary. Also, note that the following line:

    myDict["foo"]
    

    will return null if myDict is a StringDictionary, but an exception will be thrown in case of Dictionary. See the SO post he mentioned for more information, which is the source of this edit.

提交回复
热议问题