我正在使用带有联系数据的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
给定的键在词典中不存在。
我如何重构此代码以减少错误(同时仍然起作用)?
TryGetValue
方法似乎是最好的选择,因为我找到了以下页面:goo.gl/7YN6 ...但我不确定如何使用它。在我上面的代码中,row
是一个'DataRow'对象,因此我不确定您的示例代码是否正确……