代码之家  ›  专栏  ›  技术社区  ›  Slee

存储/查找名称-值对的最佳方法

  •  3
  • Slee  · 技术社区  · 17 年前

    我有一个需要参考的错误代码列表,有点像这样:

    Code / Error Message  
    A01 = whatever error  
    U01 = another error  
    U02 = yet another error type
    

    我通过web服务调用收到返回的代码,我需要显示或获取可读错误。因此,当传递一个代码时,我需要一个函数来返回可读的描述。我只是想做一个精选的案例,但我认为他们可能是更好的方法。做这件事的最好/最有效的方法是什么?

    2 回复  |  直到 17 年前
        1
  •  8
  •   FlySwat    17 年前

    使用字典(在C#中,但概念和类是相同的):

    // Initialize this once, and store it in the ASP.NET Cache.
    Dictionary<String,String> errorCodes = new Dictionary<String,String>();
    
    errorCodes.Add("A01", "Whatever Error");
    errorCodes.Add("U01", "Another Error");
    
    
    // And to get your error code:
    
    string ErrCode = errorCodes[ErrorCodeFromWS];
    
        2
  •  0
  •   nlaq    17 年前

    你会用字典。字典在内部使用hashmap来提高性能,因此在这方面是很好的。此外,由于您希望通过声音尽快完成此操作,我会在它自己的类中静态初始化它,而不是在XML文件或slimier中。你可能想要这样的东西:

    public static class ErrorCodes
    {
        private static Dictonary<string, string> s_codes = new Dicontary<string, string>();
        static ErrorCodes()
        {
             s_codes["code"] = "Description";
             s_codes["code2"] = "Description2";
        }
    
        public static string GetDesc(string code)
        {
             return s_codes[code];
        }
    }
    

    这样,如果你想将后端移动到一个文件而不是静态的,那么你可以这样做。

    推荐文章