List readonly with a private set

后端 未结 15 1926
北海茫月
北海茫月 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:02

    If you want readonly collection use ReadOnlyCollection<T>, not List<T>:

    public ReadOnlyCollection<string> MyList { get; private set; }
    
    0 讨论(0)
  • 2020-11-30 02:02
        private List<string> _items = new List<string>();         
    
        public ReadOnlyCollection<string> Items
    
        {
    
            get { return _items.AsReadOnly(); }
    
            private set { _items = value }
    
        }
    
    0 讨论(0)
  • 2020-11-30 02:07

    In the .NET 4.5 framework you can expose only the IReadOnlyList interface. Something like:

    private List<string> _mylist;
    public IReadOnlyList<string> myList { get {return _myList;} }
    

    or if you want to prevent unwanted casting to IList

    private List<string> _mylist;
    public IReadOnlyList<string> myList { get {return new List<string>(_myList);} }
    
    0 讨论(0)
  • 2020-11-30 02:08

    I prefer to use IEnumerable

    private readonly List<string> _list = new List<string>();
    
    public IEnumerable<string> Values // Adding is not allowed - only iteration
    {
       get { return _list; }
    }
    
    0 讨论(0)
  • 2020-11-30 02:10

    Return a ReadOnlyCollection, which implements IList<>

    private List<string> myList;
    
    public IList<string> MyList
    {
      get{return myList.AsReadOnly();}
    }
    
    0 讨论(0)
  • 2020-11-30 02:12

    There's a collection called ReadOnlyCollection<T> - is that what you're looking for?

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