本文介绍了IDictionary< TKey,TValue>在.NET 4中不协调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.NET 4 / Silverlight 4中的 IDictionary< TKey,TValue> 不支持协方差,即我不能执行

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< T> s现在。

analog to what I can do with IEnumerable<T>s now.

可能归结为 KeyValuePair< TKey,TValue> 也不是协变的。我觉得在词典中应该允许协方差至少为这些值。

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.

那么是一个bug还是一个功能?是否会来,可能在.NET 37.4?

So is that a bug or a feature? Will it ever come, maybe in .NET 37.4?

更新(2年后):

成为,但它不会是:·/ ,因为它来源于 IEnumerable< KeyValuePair< TKey,TValue> KeyValuePair< TKey,TValue> 不是界面,因此不能是协变

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.

BCL团队必须重新设计很多,并使用一些 ICovariantPair&TK。,TValue> 代替。对于协变接口,强大类型的索引器也不可能使用[TKey key] 。类似的结局只能通过在内部必须调用的某个地方放置一个扩展方法 GetValue(this IReadOnlyDictionary< TKey,TValue> self,TKey key)一个实际的实现,可以说是一个相当混乱的方法。

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< T& / code>是一个只读接口。 T type参数只在其输出位置( Current 属性的返回类型),因此, code> IEnumerable< string> 作为 IEnumerable< object>

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中不协调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-29 03:39