我正在使用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()
),它不存在,然后抛出一个异常:
< p > 500 < br / > .字典中不存在给定的键
我该如何重构这段代码来减少吸吮(同时仍然具有功能性)?