我正在使用带有联系人数据的 Exchange Web 服务托管 API。我有以下代码,它是 功能性 的,但并不理想:
foreach (Contact c in contactList) { string openItemUrl = "https://" + service.Url.Host + "/owa/" + c.WebClientReadFormQueryString; row = table.NewRow(); row["FileAs"] = c.FileAs; row["GivenName"] = c.GivenName; row["Surname"] = c.Surname; row["CompanyName"] = c.CompanyName; row["Link"] = openItemUrl; //home address try { row["HomeStreet"] = c.PhysicalAddresses[PhysicalAddressKey.Home].Street.ToString(); } catch (Exception e) { } try { row["HomeCity"] = c.PhysicalAddresses[PhysicalAddressKey.Home].City.ToString(); } catch (Exception e) { } try { row["HomeState"] = c.PhysicalAddresses[PhysicalAddressKey.Home].State.ToString(); } catch (Exception e) { } try { row["HomeZip"] = c.PhysicalAddresses[PhysicalAddressKey.Home].PostalCode.ToString(); } catch (Exception e) { } try { row["HomeCountry"] = c.PhysicalAddresses[PhysicalAddressKey.Home].CountryOrRegion.ToString(); } catch (Exception e) { } //and so on for all kinds of other contact-related fields... }
正如我所说,这段代码 有效 。现在,如果可能的话,我想让它吸 得少一点。
我找不到任何方法允许我在尝试访问它之前检查字典中的键是否存在,如果我尝试读取它(使用.ToString())并且它不存在,则会引发异常:
.ToString()
500 给定的键不在字典中。
我怎样才能重构这段代码以减少吸收(同时仍然有效)?
您可以使用ContainsKey:
ContainsKey
if (dict.ContainsKey(key)) { ... }
或TryGetValue:
TryGetValue
dict.TryGetValue(key, out value);
更新 :根据评论,这里的实际类不是 anIDictionary而是 a PhysicalAddressDictionary,所以方法是Contains并且TryGetValue它们以相同的方式工作。
IDictionary
PhysicalAddressDictionary
Contains
示例用法:
PhysicalAddressEntry entry; PhysicalAddressKey key = c.PhysicalAddresses[PhysicalAddressKey.Home].Street; if (c.PhysicalAddresses.TryGetValue(key, out entry)) { row["HomeStreet"] = entry; }
更新 2: 这是工作代码(由提问者编译)
PhysicalAddressEntry entry; PhysicalAddressKey key = PhysicalAddressKey.Home; if (c.PhysicalAddresses.TryGetValue(key, out entry)) { if (entry.Street != null) { row["HomeStreet"] = entry.Street.ToString(); } }
…根据需要为每个所需的键重复内部条件。每个 PhysicalAddressKey(家庭、工作等)仅执行一次 TryGetValue。