Best practice: How to expose a read-only ICollection

前端 未结 7 1694
礼貌的吻别
礼貌的吻别 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.

    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's constructor.

提交回复
热议问题