Best way to handle a KeyNotFoundException

后端 未结 6 1530
再見小時候
再見小時候 2021-01-31 01:26

I am using a dictionary to perform lookups for a program I am working on. I run a bunch of keys through the dictionary, and I expect some keys to not have a value. I catch the

6条回答
  •  别跟我提以往
    2021-01-31 02:06

    Here is a one line solution (Keep in mind this makes the lookup twice. See below for the tryGetValue version of this which should be used in long-running loops.)

    string value = dictionary.ContainsKey(key) ? dictionary[key] : "default";
    

    Yet I find myself having to do this everytime I access a dictionary. I would prefer it return null so I can just write:

    string value = dictionary[key] ?? "default";//this doesn't work
    

提交回复
热议问题