Declare a Dictionary inside a static class

后端 未结 9 1233
無奈伤痛
無奈伤痛 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:39

    The problem with your initial example was primarily due to the use of const rather than static; you can't create a non-null const reference in C#.

    I believe this would also have worked:

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

    Also, as Y Low points out, adding readonly is a good idea as well, and none of the modifiers discussed here will prevent the dictionary itself from being modified.

提交回复
热议问题