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

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

    You can use ReadOnlyCollection - wrap your collection in this and return the ReadOnlyCollection to users of your class:

    return new ReadOnlyCollection(innerCollection);
    

    Or using the AsReadOnly method of the List class:

    return innerCollection.AsReadOnly();
    

    The IEnumerable interface will do what you need, as it only has one member GetEnumerator(), that will only let you iterate over items.

提交回复
热议问题