有没有办法调用Dictionary<string, int>
一次找到一个键的值?现在我正在打两个电话。
if(_dictionary.ContainsKey("key") {
int _value = _dictionary["key"];
}
我想这样做:
object _value = _dictionary["key"]
//but this one is throwing exception if there is no such key
如果没有这样的键,我会想要 null 还是通过一次调用获取值?
最佳答案
您可以使用 TryGetValue
int value;
bool exists = _dictionary.TryGetValue("key", out value);
TryGetValue
如果它包含指定的键则返回 true,否则返回 false。
关于c# - 字典包含键并在一个函数中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17385913/