List readonly with a private set

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

    You can use List's AsReadOnly() method to return a read-only wrapper.

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

    You could also create your normal list, but expose it through a property of type IEnumerable

    private List<int> _list = new List<int>();
    
    public IEnumerable<int> publicCollection{
       get { return _list; }
    }
    
    0 讨论(0)
  • 2020-11-30 02:21

    Here is one way

    public class MyClass
        {
            private List<string> _myList;
            public ReadOnlyCollection<string> PublicReadOnlyList { get { return _myList.AsReadOnly(); } }
    
            public MyClass()
            {
                _myList = new List<string>();
                _myList.Add("tesT");
                _myList.Add("tesT1");
                _myList.Add("tesT2");
    
                //(_myList.AsReadOnly() as List<string>).Add("test 5");
            }
    
        }
    
    0 讨论(0)
提交回复
热议问题