我正在使用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 给定的键在字典中不存在。

我该如何重构这段代码来减少吸吮(同时仍然具有功能性)?


PhysicalAddressDictionary。TryGetValue

 public bool TryGetValue (
    PhysicalAddressKey key,
    out PhysicalAddressEntry physicalAddress
     )

c.PhysicalAddresses的类型是什么?如果Dictionary<TKey,TValue>,则可以使用ContainsKey方法。


你可以使用ContainsKey:

if (dict.ContainsKey(key)) { ... }

或TryGetValue:

dict.TryGetValue(key, out value);

更新:根据注释,这里的实际类不是一个字典,而是一个PhysicalAddressDictionary,所以方法是Contains和TryGetValue,但它们以相同的方式工作。

使用示例:

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();
    }
}

...对于所需的每个键,需要重复内部条件。TryGetValue只对每个PhysicalAddressKey (Home, Work等)执行一次。


这是我今天做的一点东西。似乎对我有用。基本上,您在基本名称空间中重写Add方法以进行检查,然后调用基本名称空间的Add方法以实际添加它。希望这对你有用

using System;
using System.Collections.Generic;
using System.Collections;

namespace Main
{
    internal partial class Dictionary<TKey, TValue> : System.Collections.Generic.Dictionary<TKey, TValue>
    {
        internal new virtual void Add(TKey key, TValue value)
        {   
            if (!base.ContainsKey(key))
            {
                base.Add(key, value);
            }
        }
    }

    internal partial class List<T> : System.Collections.Generic.List<T>
    {
        internal new virtual void Add(T item)
        {
            if (!base.Contains(item))
            {
                base.Add(item);
            }
        }
    }

    public class Program
    {
        public static void Main()
        {
            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(1,"b");
            dic.Add(1,"a");
            dic.Add(2,"c");
            dic.Add(1, "b");
            dic.Add(1, "a");
            dic.Add(2, "c");

            string val = "";
            dic.TryGetValue(1, out val);

            Console.WriteLine(val);
            Console.WriteLine(dic.Count.ToString());


            List<string> lst = new List<string>();
            lst.Add("b");
            lst.Add("a");
            lst.Add("c");
            lst.Add("b");
            lst.Add("a");
            lst.Add("c");

            Console.WriteLine(lst[2]);
            Console.WriteLine(lst.Count.ToString());
        }
    }
}

我使用字典,因为重复性和可能丢失的键,我很快拼凑了一个小方法:

 private static string GetKey(IReadOnlyDictionary<string, string> dictValues, string keyValue)
 {
     return dictValues.ContainsKey(keyValue) ? dictValues[keyValue] : "";
 }

叫它:

var entry = GetKey(dictList,"KeyValue1");

完成工作。


一个改进的JohanE答案,具有泛型支持,并作为扩展方法:

public static TValue GetKey<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dict, TKey key)
{
    return dict.ContainsKey(key) ? dict[key] : default;
}

叫它:

var entry = dict.GetKey("Key");