c# - 如何获取 null 而不是 KeyNotFoundException 按键访问字典值?

标签 c# dictionary

<分区>

在某些特定情况下,在按键访问字典值时,使用一种简短易读的方式来获取 null 而不是 KeyNotFoundException 似乎对我很有用, 当字典中没有这样的键时。

我首先想到的是扩展方法:

public static U GetValueByKeyOrNull<T, U>(this Dictionary<T, U> dict, T key)
        where U : class //it's acceptable for me to have this constraint
{
    if (dict.ContainsKey(key))
        return dict[key];
    else 
        //it could be default(U) to use without U class constraint
        //however, I didn't need this.
        return null; 
}

但实际上并不是很简短,当你这样写的时候:

string.Format("{0}:{1};{2}:{3}",                                                 
              dict.GetValueByKeyOrNull("key1"),
              dict.GetValueByKeyOrNull("key2"),
              dict.GetValueByKeyOrNull("key3"),
              dict.GetValueByKeyOrNull("key4"));

我想说,如果有一些接近基本语法的东西会更好:dict["key4"]

然后我想出了一个想法,让一个类有一个private 字典字段,它暴露了我需要的功能:

public class MyDictionary<T, U> //here I may add any of interfaces, implemented
                                //by dictionary itself to get an opportunity to,
                                //say, use foreach, etc. and implement them
                                // using the dictionary field.
        where U : class
{
    private Dictionary<T, U> dict;

    public MyDictionary()
    {
        dict = new Dictionary<T, U>();
    }

    public U this[T key]
    {
        get
        {
            if (dict.ContainsKey(key))
                return dict[key];
            else
                return null;
        }
        set
        {
            dict[key] = value;
        }
    }
}

但是要对基本行为进行微小的更改似乎有点开销。

另一种解决方法是在当前上下文中定义一个 Func,如下所示:

Func<string, string> GetDictValueByKeyOrNull = (key) =>
{
    if (dict.ContainsKey(key))
        return dict[key];
    else
        return null;
};

因此它可以像 GetDictValueByKeyOrNull("key1") 那样使用。

能否请您给我更多建议或帮助我选择更好的?

最佳答案

这是我个人库中的解决方案,作为扩展方法实现。我发布它只是因为它是从字典 interface 实现的,并允许传入一个可选的默认值。

实现

public static TV GetValue<TK, TV>(this IDictionary<TK, TV> dict, TK key, TV defaultValue = default(TV))
{
    TV value;
    return dict.TryGetValue(key, out value) ? value : defaultValue;
}

用法

 MyDictionary.GetValue("key1");
 MyDictionary.GetValue("key2", -1);
 MyDictionary.GetValue("key3")?.SomeMethod();

关于c# - 如何获取 null 而不是 KeyNotFoundException 按键访问字典值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14150508/

相关文章:

c# - 有没有办法跟踪字典中项目的顺序?

c# - 如何从虚假网站获取 Sitecore 项目

python - 在 Python 中动态计算 csv 列的出现次数

c# - ASP.NET MVC 3 : Editor templates for fields

c# - 如何使用c#制作完整文件夹的rar文件

c# - Visual Studio 2010 中是否有可用的 ToString() 生成器?

python - 字典到数据框

Python:按值对以元组为键的字典进行排序

python - 打印 Python 字典中的所有唯一值

c# - 在 LinqPAD 中将字典列表可视化为数据网格?