如何获得空,而不是通过KeyNotFoundException访问关键词典的价值? [英] How to get null instead of the KeyNotFoundException accessing Dictionary value by key?

查看:73
本文介绍了如何获得空,而不是通过KeyNotFoundException访问关键词典的价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些特定情况下它似乎是有用的,让我有一个短期的口语,阅读的方式来获得而不是 KeyNotFoundException 同时通过键,当出现在字典中没有这样的键访问字典值。

In some certain scenario it appeared to be useful for me to have a short-spoken, readable way to get null instead of the KeyNotFoundException while accessing dictionary value by key, when there is no such key in the dictionary.

这是我脑子里浮现的第一件事是一个扩展方法

The first thing that came into my mind was an extension method:

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



但它不是很短的细语实际上,当你写的东西是这样的:

But it's not very short-spoken actually, when you write something like this:

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



我会说,这将是更好的接近havesomething基地语法:字典[KEY4]

然后,我想出了一个主意,有一个类私人词典场,里面露出我所需要的功能:

Then I came up with an idea to have a class with a private dictionary field, which exposed the functionality I need:

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



但它似乎是一个小的开销得到的基本行为的细微变化。

But it seems a little overhead to get the slight change in the basic behaviour.

还有一个解决办法可能是在目前定义函数功能背景是这样的:

One more workaround could be to define a Func in the current context like this:

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



所以它可以利用像 GetDictValueByKeyOrNull(KEY1)

你能不能,请给我任何建议或帮助选择一个更好的?

Could you, please, give me any more suggestions or help to choose a better one?

推荐答案

在最后,我想出了一个变种利用具有显式接口实现字典类派生:

In the end I came up with a variant using a deriving from dictionary class with explicit interface implementation:

public interface INullValueDictionary<T, U>
    where U : class
{
    U this[T key] { get; }
}

public class NullValueDictionary<T, U> : Dictionary<T, U>, INullValueDictionary<T, U>
    where U : class
{
    U INullValueDictionary<T, U>.this[T key]
    {
        get
        {
            U val;
            dict.TryGet(key, out val);
            return val;
        }
    }
}



所以它暴露的功能我需要以下方式:

So it exposes the functionality I need the following way:

//create some dictionary
NullValueDictionary<int, string> dict = new NullValueDictionary<int, string>
{
    {1,"one"}
};
//have a reference to the interface
INullValueDictionary<int, string> idict = dict;

try
{
    //this throws an exception, as the base class implementation is utilized
    Console.WriteLine(dict[2] ?? "null");
}
catch { }
//this prints null, as the explicit interface implementation 
//in the derived class is used
Console.WriteLine(idict[2] ?? "null");

这篇关于如何获得空,而不是通过KeyNotFoundException访问关键词典的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆