Prevent other classes from altering a list in a class

后端 未结 4 1465
深忆病人
深忆病人 2020-12-06 05:53

If I have a class that contains, for example, a List and I want other classes to be able to see the list but not set it, I can declare



        
相关标签:
4条回答
  • 2020-12-06 06:33

    You won't be able to use an autoproperty.

    public class SomeClass()
    {
        private List<string> someList;
        public IList<string> SomeList { 
            get { return someList.AsReadOnly(); }
        }
    }
    
    0 讨论(0)
  • 2020-12-06 06:46
    public class SomeClass()
    {
        private List<string> _someList = new List<string>();
    
        public IList<string> SomeList 
        { 
             get { return _someList.AsReadOnly(); } 
        }
    }
    
    0 讨论(0)
  • 2020-12-06 06:49

    Return IEnumerable<string>, which is immutable. The getter should look like this:

    public IEnumerable<string> SomeList
    {
       get
       {
          foreach(string s in someList) yield return s; // excuse my inline style here, zealots
          yield break;
       }
    }
    
    0 讨论(0)
  • 2020-12-06 06:57

    You'll want to return the list as a ReadOnly list. You can do this with the following code:

    using System.Collections.ObjectModel;
    
    public ReadOnlyCollection<string> GetList() {
        return SomeList.AsReadOnly();
    }
    
    0 讨论(0)
提交回复
热议问题