Is there a .NET collection interface that prevents adding objects?

前端 未结 7 1673
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-18 18:13

I have a class that maintains list of objects of another class. List of objects is a public property. I would like to prevent users from adding and removing objects directly

7条回答
  •  执笔经年
    2020-12-18 18:39

    Maybe AsReadOnly method will do the trick, to hand a read-only instance to public.

    Otherwise, IEnumerable has no Add nor Remove, so you can do something like:

    private List _myList;
    public IEnumerable MyList
    {
       get
       {
          return this._myList.ToList();
       }
    }
    

    I would rather go for the IEnumerable (+ copy) as for ReadOnlyCollection, because: changes to your base list (which your read-only collection is created from) will immediately show up in your instance of the read-only collection. this may cause locking and straaange problems :)

提交回复
热议问题