我正在使用带有联系人数据的 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()
)并且它不存在,则会引发异常:
500
给定的键不在字典中。
我怎样才能重构这段代码以减少吸收(同时仍然有效)?