带接口的字典声明错误 [英] Declaration Error of Dictionary with Interface

查看:93
本文介绍了带接口的字典声明错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我试图声明一个字典有一个字符串作为键,一个对象是一个值。我在接口的帮助下声明了它。这是我的代码

Hi,

I tried to declare a dictionary have a string as the key and an object a the value. I declared it with the help of the interfaces. This is my code

ICollection<KeyValuePair<string, ICollection<DemoProperty>>> Test = new Dictionary<string, List<DemoProperty>>();





它得到了转换错误。



但是当我声明如下时没有错误



Its getting the coversion Error.

But there is no Error when I declare as below

ICollection<KeyValuePair<string, ICollection<DemoProperty>>> Test = new List<KeyValuePair<string, ICollection<DemoProperty>>>();





我知道这可以声明如下



and I know this can declare as below also

Dictionary<string, ICollection<DemoProperty>> Test = new Dictionary<string, ICollection<DemoProperty>> 





第一个陈述的确切错误是什么,如何进行第一次陈述。希望大家都能理解我的问题。



What is the exact error on the first statement and how can I proceed with the first statatement. Hope you all understand my questions.

推荐答案

你不能在字典声明中重铸价值类型:



You cannot recast the value type at declaration of the dictionary:

ICollection<keyvaluepair><string,>>> Test = new Dictionary<string,>>();

Test.Add(new KeyValuePair<string,>>("a",new List<demoproperty>()));

</demoproperty></keyvaluepair>





如果可以,那么您将无法添加任何 ICollection ,只有列表< demoproperty> 这不是你的声明所说的





您可以将 ICollection< x> 实例化为词典< x> ,因为词典< tkey,tvalue> ;继承ICollection< tkey,tvalue>但是如果你改变泛型类型,那么它们将不匹配。



If you could then you would not be able to add any ICollection, only List<demoproperty> which is not what your declaration states


You can instantiate an ICollection<x> as a Dictionary<x> because Dictionary<tkey,tvalue>; inherits ICollection<tkey,tvalue> but if you change the generic types then they won't match.


在你的第一个声明中,你使用List而不是ICollection。这适用:

In your first declaration you use List instead of ICollection. This works:
ICollection<KeyValuePair<string, ICollection<DemoProperty>>> Test = new Dictionary<string, ICollection<DemoProperty>>();


这篇关于带接口的字典声明错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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