问题描述
在的IDictionary< TKEY的,TValue>
在.NET 4 / Silverlight 4的不支持的协方差,即我不能做
The IDictionary<TKey, TValue>
in .NET 4 / Silverlight 4 does not support covariance, i.e. I can't do a
IDictionary<string, object> myDict = new Dictionary<string, string>();
模拟什么,我可以用的IEnumerable&LT做; T&GT;
取值现在
大概可以归结为 KeyValuePair&LT; TKEY的,TValue&GT;
不是协变要么。我觉得,协方差应该被允许在字典至少值。
Probably boils down to the KeyValuePair<TKey, TValue>
not being covariant either. I feel that covariance should be allowed in dictionaries at least for the values.
所以是一个错误或功能?他会不会来,也许在.NET 37.4?
So is that a bug or a feature? Will it ever come, maybe in .NET 37.4?
更新(2年后):
将有一个<$c$c>IReadOnlyDictionary<TKey, TValue&GT; 在.NET 4.5,但它不会是协变的既:·/
,因为它派生自的IEnumerable&LT; KeyValuePair&LT; TKEY的,TValue&GT;&GT;
和 KeyValuePair&LT; TKEY的,TValue&GT;
不是接口,因此不能协变
There will be an IReadOnlyDictionary<TKey, TValue>
in .NET 4.5, but it won't be covariant either :·/
, because it derives from IEnumerable<KeyValuePair<TKey, TValue>>
, and KeyValuePair<TKey, TValue>
is not an interface and thus cannot be covariant.
首创置业团队将不得不重新设计了许多上来,并使用一些 ICovariantPair&LT; TKEY的,TValue&GT;
代替。同时强类型的索引点菜此[TKEY的关键]
是不可能的协变接口。类似的下场只能放置一个扩展方法来实现的GetValue&LT;&GT;(这IReadOnlyDictionary&LT; TKEY的,TValue&GT;自我,TKEY的键)
地方这会在一定程度内必须调用在实际实施中,这可以说是看起来像一个相当混乱的办法。
The BCL team would have to redesign a lot to come up and use some ICovariantPair<TKey, TValue>
instead. Also strongly-typed indexers á la this[TKey key]
aren't possible for covariant interfaces. A similar end can only be achieved by placing an extension method GetValue<>(this IReadOnlyDictionary<TKey, TValue> self, TKey key)
somewhere which would somehow internally have to call an an actual implementation, which arguably looks like a quite messy approach.
推荐答案
这是一个特点。 .NET 4.0只支持安全协方差。你提到的转换是潜在的危险,你可以添加一个非字符串元素,如果这是可能的字典:
It's a feature. .NET 4.0 only supports safe covariance. The cast you mentioned is potentially dangerous as you could add a non-string element to the dictionary if that was possible:
IDictionary<string, object> myDict = new Dictionary<string, string>();
myDict["hello"] = 5; // not an string
在另一方面,的IEnumerable&LT; T&GT;
是一个只读接口。该 T
键入参数只在它的输出位置(当前
属性的返回类型),所以它是安全的治疗的IEnumerable&LT;字符串&GT;
为的IEnumerable&LT;对象&gt;
On the other hand, IEnumerable<T>
is a read-only interface. The T
type parameter is only in its output positions (return type of the Current
property) so it's safe to treat IEnumerable<string>
as an IEnumerable<object>
.
这篇关于IDictionary的&LT; TKEY的,TValue&GT;在.NET 4中不是协变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!