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

前端 未结 7 1672
爱一瞬间的悲伤
爱一瞬间的悲伤 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:37

    Out of the box, only IEnumerable will provide this without exposing any Add and Remove public methods that might trick the client into getting a runtime exception.

    If you want your public API to explicitely state that the collection is read-only and you need an indexer, you will have to write your own wrapper around existing List or T[].

提交回复
热议问题