代码之家  ›  专栏  ›  技术社区  ›  Andras Zoltan

为什么字典没有IEnumerable<KeyValuePair<TKey,TValue>>向量?

  •  14
  • Andras Zoltan  · 技术社区  · 16 年前

    Dictionary<TKey, TValue> IEnumerable<KeyValuePair<TKey, TValue>> List<T> ctor(IEnumerable<T> range) ?

    IDictionary<TKey, TValue> IEnumerable<键值对<TKey,TValue>&燃气轮机; ,IEnumerable选项肯定更有意义;除非 IEnumerable<>

    更糟糕的是,如果您查看ctor的IDictionary版本的实现,输入字典将使用以下代码导入:

    foreach (KeyValuePair<TKey, TValue> pair in dictionary)
    {
        this.Add(pair.Key, pair.Value);
    }
    

    有没有人能想出一个很好的理由来解释为什么框架设计人员选择了最具体的接口,而基本接口就是所需的全部?

    Mark Seeman建议避免重复密钥引发的例外——这很可能接近事实——但请考虑这个例子:

    [TestMethod]
    [ExpectedException(typeof(ArgumentException))]
    public void How_To_Break_The_IDictionary_Ctor_Design_Decision()
    {
      Dictionary<string, string> dictionary = new Dictionary<string, string>();
      dictionary.Add("hello", "world");
      dictionary.Add("Hello", "world");
    
      Dictionary<string, string> dictionary2 = 
        new Dictionary<string, string>(dictionary,
                                       StringComparer.CurrentCultureIgnoreCase);
    }
    

    我知道-测试结果是相反的-但出于某种原因,我认为它使我的观点更好:)

    如果键比较器不是IDictionary接口的一部分,则可以 从未 ArgumentException ,在构建新的。

    2 回复  |  直到 16 年前
        1
  •  13
  •   Mark Seemann    16 年前

    非官方猜测 :

    IEnumerable<KeyValuePair<TKey, TValue>> 您可以使用同一个键提供多个项,这将是什么预期行为?

    例如,你可以这样做:

    var kvps = new[]
    {
        new KeyValuePair<int, string>(1, "Foo"),
        new KeyValuePair<int, string>(1, "Bar"),
        new KeyValuePair<int, string>(1, "Baz")        
    }
    var dic = new Dictionary<int, string>(kvps);
    

    您可能会认为这应该只是抛出一个与Add方法的行为一致的异常,但我猜设计团队认为这将是一个比实际有用的更大的混乱来源。。。

        2
  •  2
  •   Amy B    16 年前
      public static Dictionary<T, U> ToDictionary(
          this IEnumerable<KeyValuePair<T, U>> source)
      {
        return source.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
      }