List readonly with a private set

后端 未结 15 2008
北海茫月
北海茫月 2020-11-30 01:57

How can I expose a List so that it is readonly, but can be set privately?

This doesn\'t work:

public List myList          


        
15条回答
  •  隐瞒了意图╮
    2020-11-30 02:16

    A bit late, but nevertheless: I don't like using the ReadOnlyCollection wrapper because it still exposes all the methods for modifying the collection, which all throw a NotSupportedException when accessed in run-time. In other words, it implements the IList interface, but then violates this same contract in run-time.

    To express that I am really exposing an immutable list, I usually resort to a custom IIndexable interface, which adds Length and an indexer to an IEnumerable (described in this CodeProject article). It is a wrapper as it should have been done in the first place IMHO.

提交回复
热议问题