【问题标题】:How to avoid null key errors in dictionary?如何避免字典中的空键错误?
【发布时间】:2010-11-03 10:17:51
【问题描述】:

key为null时如何避免出错?

//Getter/setter
public static Dictionary<string, string> Dictionary
{
    get { return Global.dictionary; }
    set { Global.dictionary = value; }
}

更新:

Dictionary.Add("Key1", "Text1");
Dictionary["Key2"] <-error! so what can I write in the GET to avoid error?

谢谢。

问候

【问题讨论】:

  • 代码不符合问题...你的钥匙在哪里?

标签: c# static-methods


【解决方案1】:

使用TryGetValue:

Dictionary<int, string> dict = ...;
string value;

if (dict.TryGetValue(key, out value))
{
    // value found
    return value;
}
else
{
    // value not found, return what you want
}

【讨论】:

  • +1使用 try 方法,如果要检索值,请不要使用 contains 方法,因为您将有效地进行两次查找,因此效率低下
  • 这个答案是不正确的:TryGetValue 如果 key 为 null 则抛出异常。
  • @JasonBaley 不确定这与答案有关,Dictionary 不支持空键。可以在此线程中找到其他讨论:stackoverflow.com/questions/4632945/dictionary-with-null-key
  • @Grozz 问题是如何避免在为字典中的查找提供空键时出现错误。将 null 键传递给 TryGetValue 仍然会引发错误,因此它不会回答问题。在您的回答中,如果key 为空,则会引发异常,那么这如何解决原始问题?他试图避免异常。
  • @JasonBaley 请仔细阅读整个问题,而不仅仅是标题
【解决方案2】:

您可以使用Dictionary.ContainsKey 方法。

所以你会写:

if (myDictionary.ContainsKey("Key2"))
{
    // Do something.
}

其他替代方法是将访问权限包装在 try...catch 块中或使用 TryGetValue(请参阅链接到的 MSDN 页面上的示例)。

string result = null;
if (dict.TryGetValue("Key2", out result))
{
    // Do something with result
}

如果您想对结果执行某些操作,TryGetMethod 会更有效,因为您不需要第二次调用来获取值(就像使用 ContainsKey 方法一样)。

(当然,在这两种方法中,您都可以将“Key2”替换为变量。)

【讨论】:

  • 我的意思不是在方法中,而是在声明中!
  • @eman - 那我不明白你的问题。您能否更新代码以准确显示您想要实现的目标?
【解决方案3】:

一种扩展方法:

public static TValue GetValue<TKey, TValue>(this Dictionary<TKey, TValue> dic, TKey key)
{
    TValue result;
    return dic.TryGetValue(key, out result) ?
        result :
        default(TValue);
}

用法:

var dic = new Dictionary<string, string>
{
   { "key", "value" }
};

string r1 = dic.GetValue("key"); // "value"
string r2 = dic.GetValue("false"); // null

【讨论】:

    【解决方案4】:

    字典中的键永远不能为空。字典是一个哈希表,根据定义,您需要一个非空键,否则哈希函数无法映射到相应的元素。

    【讨论】:

    • 如何判断是否为空并返回空字符串?
    • 我认为这是他的问题,如何避免将 null 设置为键......尽管如此,他的代码并不完全符合这个假设。
    • 在您的代码中,您永远不会通过按键访问字典。您只需返回一个静态字典。我不明白你的意思。
    • @Bobby,这永远不会发生。如果您尝试使用 null 作为字典中的键,您将得到 ArgumentNullException,因此您永远不会拥有带有 null 键的字典。
    • 是的,我认为这是他的问题,如何避免该异常。
    【解决方案5】:

    你退回了错误的东西。不要返回字典,传入一个键并返回值。

    public static string GetValue(string key)
    {
        if(Global.dictionary.ContainsKey(key))
        {
            return Global.dictionary[key];
        }
    
        return ""; // or some other value
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-11
      • 1970-01-01
      • 2021-01-28
      • 2016-08-24
      • 2018-10-29
      • 2014-09-08
      • 1970-01-01
      相关资源
      最近更新 更多