且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

哪你preFER的接口:T [],IEnumerable的< T&GT ;,的IList< T&GT ;,还是其他?

更新时间:2022-03-13 15:02:59

我的preference是的IEnumerable< T> 。任何其他建议的接口给出允许消费者修改基础集合的外观。这是几乎可以肯定不是你想做的事,因为它是使消费者能够悄无声息修改内部集合了什么。

My preference is IEnumerable<T>. Any other of the suggested interfaces gives the appearance of allowing the consumer to modify the underlying collection. This is almost certainly not what you want to do as it's allowing consumers to silently modify an internal collection.

另一个好恕我直言,是 ReadOnlyCollection还&LT; T&GT; 。它允许所有的乐趣.Count之间和索引属性,并毫不含糊地说,消费者不能修改我的数据。

Another good one IMHO, is ReadOnlyCollection<T>. It allows for all of the fun .Count and Indexer properties and unambiguously says to the consumer "you cannot modify my data".