根据.NET API,类Dictionary<TKey, TValue>
继承自ICollection<T>
,其中T
为KeyValuePair<TKey, TValue>
。 Dictionary<TKey, TValue>
类如何隐藏它从ICollection<T>
继承的一些方法?
例如:
ICollection<T>
的方法为ICollection.Add(T item)
但是当你使用Dictionary<TKey, TValue>
对象时,它没有那个方法。您只能使用Dictionary<TKey, TValue>.Add(TKey key, TValue value)
。没有Dictionary<TKey, TValue>.Add(KeyValuePair<TKey,TValue> kvp)
方法。
任何人都知道为什么?这些方法是如何隐藏的?
答案 0 :(得分:5)
通过明确实现接口并使此实现成为私有/受保护来完成...参见
您可以随时将Dictionary
转换为ICollection
,然后致电Add
- 虽然我不会这样做,因为我不知道它是否有用......
答案 1 :(得分:4)
他们被“隐藏”使用explicit interface implementation。所以你可以使用:
ICollection<KeyValuePair<Foo, Bar>> collection = dictionary;
collection.Add(...);
根据应该工作的documentation ...虽然通常只是使用替代方法。
答案 2 :(得分:2)
因为词典具有ICollection.Add
的显式实现。在使用之前,您需要将其强制转换为ICollection<KeyValuePair<TKey,TValue>>
。
您可以在MSDN
上查看实施情况void ICollection<KeyValuePair<TKey, TValue>>.Add(
KeyValuePair<TKey, TValue> keyValuePair
)
答案 3 :(得分:1)
作为参考,明确实现的Dictionary<>
方法的ICollection<>.Add()
代码为:
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair)
{
this.Add(keyValuePair.Key, keyValuePair.Value);
}
你可以使用它,因为它只是做你自己可能做的事情。
答案 4 :(得分:1)
如果Dictionary
直接暴露了Add(KeyValuePair<TKey,TValue>)
重载,那表明如果有人KeyValuePair<TKey,TValue>
(例如,当一个人在枚举另一个字典时收到),最好将其传递给这样的方法比读出Key
和Value
属性并单独传递它们。事实上,情况恰恰相反:将整个结构传递给Add
方法,然后必须将其分解并将其成员传递给离散参数重载,效率低于将结构分解为其成员并传递它们的效率。分开。
请注意,如果Dictionary
在结构类型的数组中内部存储了以KeyValuePair<TKey,TValue>
作为字段(不是属性)的内容,则代码如下:
for var item in Dict1
{
Dict2.Add(item);
}
可能比
更有效率for var item in Dict1
{
Dict2.Add(item.Key, Item.Value);
}
但由于Dictionary
会分解任何传入的KeyValuePair
,因此没有理由鼓励使用以前的代码。