c# Dictionary.TryGetValue()的用法

当确定字典中存在该键值对时,可以使用:

myObject result = null;
if (theDictionary.ContainsKey(id))
{
    result = theDictionary[id];
    //What ever you gonna do next...
}


当在字典中不能确定是否存在该键时需要使用TryGetValue,以减少一次不必要的查找,同时避免了判断Key值是否存在而引发的“给定关键字不在字典中。”的错误。(TryGetValue是根据ID返回相应的数据,如果没有ID则返回默认值)

myObject result = null;
if (theDictionary.TryGetValue(id, out result))
{
  //What ever you gonna do next...
}


 

猜你喜欢

转载自blog.csdn.net/qq_38721111/article/details/83508909
今日推荐