The property Count from ICollection<T> is still around for backward compatibility?

倾然丶 夕夏残阳落幕 提交于 2019-12-13 10:37:58

问题


Previous Context

To understand what I'm questioning, see first the question "Why does .Count work without parentheses?"

In that question is discussed, Why exists Count (property) and Count() (method) in classes that implements ICollection<T>. that question was answered satisfactorily.

But below the answer in a comment, another question was raised by finoutlook:

The question

The property Count is still around (in later .Net versions to LINq technology) for backward compatibility?


回答1:


No, it's around so that a collection can return how many elements there are directly, without having to iterate over it.

Enumerable.Count() has an optimization such that if the collection implements ICollection<T>, it will use the property instead of iterating over the collection one element at a time, which is what you'd have to do otherwise.

It feels like a clearly useful property to me. Even if the framework were created today with LINQ in mind, I'm sure there would still be something very similar. (Admittedly I can think of various changes I'd like to see to the collection interfaces, but that's a different matter.)




回答2:


Although It can be truth (is still around for backward compatibility), in my point of view, backward compatibility is not the reason for this property still exists.

When you have a class that implement ICollection<T> in most of cases will be short way to count the elements internally (in private or protected scope of the class).

And also a collection must have knowledge of how many elements it has. As far as i am concerned, this is the main purpose of this property.



来源:https://stackoverflow.com/questions/20551124/the-property-count-from-icollectiont-is-still-around-for-backward-compatibilit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!