C#中:如何才能字典< K,V>实现ICollection的< KeyValuePair< K,V>>无需添加(KeyValuePair< K,V>)?

2023-09-03 11:04:17 作者:窻迯詴夢ヤ

看着 System.Collections.Generic.Dictionary< TKEY的,TValue> ,它清楚地农具的ICollection< KeyValuePair< TKEY的,TValue>> ,但没有必需的无效添加(KeyValuePair< TKEY的,TValue>项目)。功能

Looking at System.Collections.Generic.Dictionary<TKey, TValue>, it clearly implements ICollection<KeyValuePair<TKey, TValue>>, but doesn't have the required "void Add(KeyValuePair<TKey, TValue> item)" function.

这也可以尝试初始化时,看到了词典是这样的:

This can also be seen when trying to initialize a Dictionary like this:

private const Dictionary<string, int> PropertyIDs = new Dictionary<string, int>()
{
    new KeyValuePair<string,int>("muh", 2)
};

而失败,

没有重载方法'添加'需要'1'参数

No overload for method 'Add' takes '1' arguments

为什么会这样呢?

推荐答案

预期的API是通过两个参数添加(键,值)方法添加(或此[关键] 索引);正因为如此,它使用显式接口实现提供了添加(KeyValuePair&LT;,&GT;)。方法

The expected API is to add via the two argument Add(key,value) method (or the this[key] indexer); as such, it uses explicit interface implementation to provide the Add(KeyValuePair<,>) method.

如果您使用的IDictionary&LT;字符串,INT&GT; 接口,而不是,您将有机会获得丢失的方法(因为你不能隐藏界面上的任何东西)。

If you use the IDictionary<string, int> interface instead, you will have access to the missing method (since you can't hide anything on an interface).

此外,在集合初始化,请注意,您可以使用替代语法:

Also, with the collection initializer, note that you can use the alternative syntax:

Dictionary<string, int> PropertyIDs = new Dictionary<string, int> {
  {"abc",1}, {"def",2}, {"ghi",3}
}

它使用了添加(键,值)方法。

 
精彩推荐
图片推荐