Best practice: How to expose a read-only ICollection

前端 未结 7 1581
礼貌的吻别
礼貌的吻别 2020-12-16 02:39

I have an ICollection called foos in my class which I want to expose as read-only (see this question). I see that the interface defines a

相关标签:
7条回答
  • 2020-12-16 03:12

    I typically return an IEnumerable<T>.

    Once you make a collection readonly (so methods like Add, Remove and Clear no longer work) there's not much left that a collection supports that an enumerable doesn't - just Count and Contains, I believe.

    If consumers of your class really need to treat elements like they're in a collection, it's easy enough to pass an IEnumerable to List<T>'s constructor.

    0 讨论(0)
提交回复
热议问题