【问题标题】:best way to store / lookup name value pairs存储/查找名称值对的最佳方式
【发布时间】:2008-11-20 17:46:02
【问题描述】:

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

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

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

【问题讨论】:

  • 这是什么语言的? SQL? C#?
  • 标签似乎表示 asp.net 和 vb.net :)

标签: asp.net vb.net


【解决方案1】:

使用字典,(在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];

【讨论】:

  • 您对我们投了反对票!为什么?我们的回答没有错。哈希表(字典、哈希图)应该是众所周知的,或者至少对于任何程序员来说都很容易查找。此外,他没有说他是否使用 C#。
  • 请注意,使用 C# 3.0 和集合初始化程序,字典初始化可能更具可读性。 (诚​​然,这是一个 VB.NET 问题 - 只是大声思考。)还值得考虑将映射放在一个文件中,这样它就可以在不重建的情况下更新。
  • 他不是。显然他正在使用 VB.net。我同意您的答案不应该被否决;但除非您提供更多详细信息或实际示例,否则不一定要投赞成票。不过这只是我的看法。
【解决方案2】:

你会使用字典。字典在内部使用 hashmap 来提高性能,因此在这方面很好。此外,因为您希望它的声音尽可能快地进行,所以我会在它自己的类中静态初始化它,而不是在 XML 文件或更纤细的文件中。你可能想要这样的东西:

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

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

【讨论】:

    猜你喜欢
    • 2015-12-30
    • 1970-01-01
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多