Best practice: How to expose a read-only ICollection

前端 未结 7 1742
礼貌的吻别
礼貌的吻别 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:07

    I seem to have settled on returning IEnumerable with the objects cloned.

    public IEnumerable GetFooseList() {
       foreach(var foos in Collection) {
         yield return foos.Clone();
       }
    }
    
    • requires a Clone method on Foos.

    This allows no changes in the collection. Remember that ReadonlyCollection is "leaky" since the objects inside it can be changed as mentioned in a link in another post.

提交回复
热议问题