List readonly with a private set

后端 未结 15 1975
北海茫月
北海茫月 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条回答
  •  -上瘾入骨i
    2020-11-30 02:15

    I think you are mixing concepts.

    public List myList {get; private set;}
    

    is already "read-only". That is, outside this class, nothing can set myList to a different instance of List

    However, if you want a readonly list as in "I don't want people to be able to modify the list contents", then you need to expose a ReadOnlyCollection. You can do this via:

    private List actualList = new List();
    public ReadOnlyCollection myList
    {
      get{ return actualList.AsReadOnly();}
    }
    

    Note that in the first code snippet, others can manipulate the List, but can not change what list you have. In the second snippet, others will get a read-only list that they can not modify.

提交回复
热议问题