List readonly with a private set

后端 未结 15 1927
北海茫月
北海茫月 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:13
    private List<string> myList;
    
    public string this[int i]
    {
        get { return myList[i]; }
        set { myList[i] = value; }
    }
    
    0 讨论(0)
  • 2020-11-30 02:14

    Why are you using a List. Sounds like what you really want to expose is IEnumerable

    public IEnumerable<string> myList { get; private set; }
    

    Now users of the class can read the items but not chagnge the list.

    0 讨论(0)
  • 2020-11-30 02:14

    I didn't see this option mentioned yet:

    private List<string> myList;
    
    public List<string> MyList
    {
        get { return myList.AsReadOnly().ToList(); }
    }
    

    This should allow you to expose a read-only List.

    0 讨论(0)
  • 2020-11-30 02:15

    I think you are mixing concepts.

    public List<string> myList {get; private set;}
    

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

    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<string>. You can do this via:

    private List<string> actualList = new List<string>();
    public ReadOnlyCollection<string> 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.

    0 讨论(0)
  • 2020-11-30 02:15
    private List<string> my_list;
    
    public ReadOnlyCollection<string> myList
    {
        get { return my_list.AsReadOnly(); }
        private set { my_list = value; }
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题