Why doesn't generic ICollection implement IReadOnlyCollection in .NET 4.5?

后端 未结 6 833
北恋
北恋 2020-12-03 02:45

In .NET 4.5 / C# 5, IReadOnlyCollection is declared with a Count property:

public interface IReadOnlyCollection

        
6条回答
  •  遥遥无期
    2020-12-03 03:11

    When I first read your question I thought "Hey, he's right! That would make the most sense." But the point of an interface is to describe a contract - A description of behavior. If your class implements IReadOnlyCollection, it should be read-only. Collection isn't. So for a Collection to implement an interface that implied read-only could lead to some pretty nasty problems. Consumers of an IReadOnlyCollection are going to make certain assumptions about that underlying collection - like iterating over it is safe becuase no one can be modifying it, etc. etc. If it was structured as you suggest that might not be true!

提交回复
热议问题