Declare a Dictionary inside a static class

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

    The correct syntax ( as tested in VS 2008 SP1), is this:

    public static class ErrorCode
    {
        public static IDictionary<string, string> ErrorCodeDic;
         static ErrorCode()
        {
            ErrorCodeDic = new Dictionary<string, string>()
                { {"1", "User name or password problem"} };
        }
    }
    
    0 讨论(0)
  • 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<string, string> 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<string, string>. See the SO post he mentioned for more information, which is the source of this edit.

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

    Create a static constructor to add values in the Dictionary

    enum Commands
    {
        StudentDetail
    }
    public static class Quires
    {
        public static Dictionary<Commands, String> quire
            = new Dictionary<Commands, String>();
        static Quires()
        {
            quire.add(Commands.StudentDetail,@"SELECT * FROM student_b");
        }
    }
    
    0 讨论(0)
提交回复
热议问题