Prevent other classes from altering a list in a class

后端 未结 4 1471
深忆病人
深忆病人 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:49

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

    public IEnumerable SomeList
    {
       get
       {
          foreach(string s in someList) yield return s; // excuse my inline style here, zealots
          yield break;
       }
    }
    

提交回复
热议问题