简体   繁体   English

为什么是HashSet <T> .IsReadOnly明确吗?

[英]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 )基本上有两个原因:

  1. You implement multiple interfaces with members containing the same signatures, and you want these members to behave differently. 您使用包含相同签名的成员实现多个接口,并且您希望这些成员的行为不同。
  2. An interface member is not of particular interest to the class, but is required in order to reference objects by the interface. 接口成员对类不是特别感兴趣,但是为了通过接口引用对象是必需的。

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.

相关问题 为什么我不能预先分配一个哈希集<t></t> - Why can't I preallocate a hashset<T> 为什么HashSet <T> 没有实现IReadOnlyCollection <T> ? - Why HashSet<T> does not implement IReadOnlyCollection<T>? 为什么 IsReadOnly 被列为非公共成员? - Why is IsReadOnly listed as a non-public member? ICollection <T> 为什么在HashSet上调用SerializationBinder <T> 但不在清单上 <T> - ICollection<T> Why SerializationBinder is call on HashSet<T> but not on List<T> 如何覆盖列表 <T> .isReadOnly在C#中 - How to override List<T>.IsReadOnly in C# 为什么 Bridge.net 不编译 HashSet<t> 或堆叠<t></t></t> - Why does Bridge.net not compile HashSet<T> or Stack<T> 为什么我不能写if(object是HashSet &lt;&gt;)但是如果我写的话就没关系(object.GetType()== typeof(HashSet &lt;&gt;)) - Why can't I write if (object is HashSet<>) but it's okay if I write (object.GetType() == typeof(HashSet<>)) 为什么使用HashSet <T> 类不用于实现Enumerable.Distinct - Why HashSet<T> class is not used to implement Enumerable.Distinct 为什么是HashSet<T> 归因于 MayLeakOnAbort,但字典<K,V>不是? - Why is HashSet<T> attributed with MayLeakOnAbort, but Dictionary<K,V> not? 为什么我不能在没有枚举的情况下从HashSet中检索项目? - Why can't I retrieve an item from a HashSet without enumeration?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM