当确定字典中存在该键值对时,可以使用:
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... }
热门工具 换一换