好的,我知道构建一个提供该功能的工厂方法很简单; 但是考虑到 Dictionary<TKey, TValue>
是 IEnumerable<KeyValuePair<TKey, TValue>>
,它难道不应该有一个类似于 List<T>
的 ctor(IEnumerable<T> range)
构造函数吗?
更荒谬的是,它提供了一个接受 IDictionary<TKey, TValue>
作为源的构造函数,但由于该接口也是IEnumerable<KeyValuePair<TKey, TValue>>
,因此使用 IEnumerable 选项肯定更合理,除非在这个类最初设计时没有 IEnumerable<>
接口。
更糟糕的是,如果你查看 IDictionary 版本的 ctor 实现 - 输入的字典会用以下代码导入:
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);
}
我知道 - 这个测试是反向的 - 但出于某种原因,我认为这更能说明我的观点 :)
鉴于Key比较器不是IDictionary接口的一部分,您永远无法保证导入的字典不会生成重复的键,从而在构建新字典时引发ArgumentException。
因此,您可以使用一个执行相同操作的IEnumerable构造函数。