本文介绍了为什么 HashSet&lt;T&gt;没有实现 IReadOnlyCollection<T>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我刚刚发现 .NET Fx 现在有 3 个有用的接口:IReadOnlyCollectionIReadOnlyListIReadOnlyDictionary我有点困惑为什么 HashSet<T> 没有实现 IReadOnlyCollection?是不是有什么原因,还是微软又忘记设置了?UPD经过两个小时的谷歌搜索,我发现 BCL 中有许多集合具有 .Count 属性但没有实现 IReadOnlyCollection 接口.>UPD2我找到了这篇文章 http://social.msdn.microsoft.com/Forums/en/netfxbcl/thread/b4fb991a-3f5c-4923-93d4-7cd5c004f859 和 Immo Landwerth 的回答,他在哪里下面说除了 List 和 Dictionary 之外的其他集合是否会更新为支持这些接口吗?绝对的.事实上,我们所有的内置集合类型已经实现 IReadOnlyList 和 IReadOnlyDictionary.这意味着,你可以直接将 List、T[] 或 Dictionary 的实例传递给一个需要 IReadOnly 版本的 API. 解决方案 在 4.5 版框架中,HashSet 没有实现 IReadOnlyCollection.这个遗漏在框架的 4.6 版中得到解决(在提出上述问题后近 12 个月发布).这些更正是不限于HashSet,其他集合如Stack 和 队列; 已收到这些改进.对任何遗漏原因的猜测没有实际意义.这可能是疏忽或时间压力,但坦率地说,这无关紧要.我怀疑即使来自 Microsoft 开发团队的直接输入也会有些主观,即使我们喜欢相关的轶事.I've just found that .NET Fx now has 3 useful interfaces:IReadOnlyCollection<T>IReadOnlyList<T>IReadOnlyDictionary<K,V>And I'm bit confused why HashSet<T> do not implement IReadOnlyCollection<T>? Are there any reasons, or Microsoft just forgot about sets again?UPDAfter two-hours googling I've found that there are many collections in BCL which has .Count property but do not implement IReadOnlyCollection<T> interface.UPD2I've found this post http://social.msdn.microsoft.com/Forums/en/netfxbcl/thread/b4fb991a-3f5c-4923-93d4-7cd5c004f859 and the answer by Immo Landwerth where he've said following Will other collections besides List<> and Dictionary<> be updated to support these interfaces? Absolutely. In fact, all of our built-in collection types already implement IReadOnlyList<> and IReadOnlyDictionary<>. This means, you can directly pass an instance of List, T[] or Dictionary<> to an API that takes an IReadOnly-version of it. 解决方案 In version 4.5 of the framework, HashSet<T> does not implement IReadOnlyCollection<out T>.This omission was resolved in version 4.6 of the framework (released almost 12 months after the above question was asked).These corrections are not limited to HashSet<T>, other collections such as Stack<T> and Queue<T> have received these improvements.Speculation on the reason for any omission is moot. It may be oversight or time pressure but frankly, it is of little consequence. I suspect that even direct input from the Microsoft Development Team would be somewhat subjective, even if we enjoy associated anecdotes. 这篇关于为什么 HashSet&lt;T&gt;没有实现 IReadOnlyCollection<T>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-23 00:12