[英]Why is HashSet<T>.IsReadOnly explicit?
This 这个
var h = new HashSet<int>();
var r = h.IsReadOnly;
does not compile. 不编译。 I have to do 我要做
var r = ((ICollection<int>)h).IsReadOnly;
why wasn't IsReadOnly implemented normally? 为什么IsReadOnly没有正常实施?
(I'm not asking how , but why ) (我不是问怎么样 ,但为什么 )
I'm guessing its because, while HashSet implements ICollection, IsReadOnly has no meaning for HashSet. 我猜它是因为,当HashSet实现ICollection时,IsReadOnly对HashSet没有意义。 In fact, if you reflect it, the property always returns false. 实际上,如果您反映它,该属性始终返回false。 Implementing it explicitly hides this method from the public interface. 明确地实现它会从公共接口隐藏此方法。
Another reason is because the ICollection interface may be implemented because of incidental reasons (eg, to support xaml serialization) rather than because its necessary to the primary use of the class. 另一个原因是因为ICollection接口可能由于偶然原因(例如,支持xaml序列化)而实现,而不是因为它对于类的主要用途是必要的。 So implementing it explicitly can keep the clutter out of the class' interface. 因此,明确地实现它可以将杂乱的东西排除在类的接口之外。
There are basically two reasons why you would resort to an explicit interface implementation (source: MSDN ): 您使用显式接口实现(源: MSDN )基本上有两个原因:
For HashSet<T>
, the latter case applies, as a hash set is never read only and IsReadOnly
will thus always return false
. 对于HashSet<T>
,后一种情况适用,因为哈希集永远不会是只读的,因此IsReadOnly
将始终返回false
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.