What happens to C# Dictionary lookup if the k

2020-05-18 04:14发布

I tried checking for null but the compiler warns that this condition will never occur. What should I be looking for?

标签: c# dictionary
9条回答
走好不送
2楼-- · 2020-05-18 04:53

If you're just checking before trying to add a new value, use the ContainsKey method:

if (!openWith.ContainsKey("ht"))
{
    openWith.Add("ht", "hypertrm.exe");
}

If you're checking that the value exists, use the TryGetValue method as described in Jon Skeet's answer.

查看更多
来,给爷笑一个
3楼-- · 2020-05-18 04:58

The Dictionary throws a KeyNotFound exception in the event that the dictionary does not contain your key.

As suggested, ContainsKey is the appropriate precaution. TryGetValue is also effective.

This allows the dictionary to store a value of null more effectively. Without it behaving this way, checking for a null result from the [] operator would indicate either a null value OR the non-existance of the input key which is no good.

查看更多
趁早两清
4楼-- · 2020-05-18 04:59

Consider the option of encapsulating this particular dictionary and provide a method to return the value for that key:

public static class NumbersAdapter
{
    private static readonly Dictionary<string, string> Mapping = new Dictionary<string, string>
    {
        ["1"] = "One",
        ["2"] = "Two",
        ["3"] = "Three"
    };

    public static string GetValue(string key)
    {
        return Mapping.ContainsKey(key) ? Mapping[key] : key;
    }
}

Then you can manage the behaviour of this dictionary.

For example here: if the dictionary doesn't have the key, it returns key that you pass by parameter.

查看更多
登录 后发表回答