Declare a Dictionary inside a static class

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

    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" }
    };
    

    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.

    Check out ReadOnlyCollection for reference.

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

    0 讨论(0)
  • 2020-12-23 11:23

    You can use the static/class constructor to initialize your dictionary:

    public static class ErrorCode
    {
        public const IDictionary<string, string> ErrorCodeDic;
        public static ErrorCode()
        {
            ErrorCodeDic = new Dictionary<string, string>()
                { {"1", "User name or password problem"} };
        }
    }
    
    0 讨论(0)
  • 2020-12-23 11:24

    OK - so I'm working in ASP 2.x (not my choice...but hey who's bitching?).

    None of the initialize Dictionary examples would work. Then I came across this: http://kozmic.pl/archive/2008/03/13/framework-tips-viii-initializing-dictionaries-and-collections.aspx

    ...which hipped me to the fact that one can't use collections initialization in ASP 2.x.

    0 讨论(0)
  • 2020-12-23 11:35

    Make the Dictionary a static, and never add to it outside of your static object's ctor. That seems to be a simpler solution than fiddling with the static/const rules in C#.

    0 讨论(0)
  • 2020-12-23 11:35
    public static class ErrorCode
    {
        public const IDictionary<string , string > m_ErrorCodeDic;
    
        public static ErrorCode()
        {
          m_ErrorCodeDic = new Dictionary<string, string>()
                 { {"1","User name or password problem"} };             
        }
    }
    

    Probably initialise in the constructor.

    0 讨论(0)
  • 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<string, string> ErrorCodeDic
            = new Dictionary<string, string>()
                { {"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.

    0 讨论(0)
提交回复
热议问题