C#中:如何才能字典< K,V>实现ICollection的< KeyValuePair< K,V>>无需添加(KeyValuePair< K,V>)? [英] C#: How can Dictionary<K,V> implement ICollection<KeyValuePair<K,V>> without having Add(KeyValuePair<K,V>)?

查看:132
本文介绍了C#中:如何才能字典< K,V>实现ICollection的< KeyValuePair< K,V>>无需添加(KeyValuePair< K,V>)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看着 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}
}

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

这篇关于C#中:如何才能字典&LT; K,V&GT;实现ICollection的&LT; KeyValuePair&LT; K,V&GT;&GT;无需添加(KeyValuePair&LT; K,V&GT;)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆