代码之家  ›  专栏  ›  技术社区  ›  Michael Todd

阻止其他类更改类中的列表

c#
  •  7
  • Michael Todd  · 技术社区  · 16 年前

    例如,如果我有一个类包含一个列表<string>,并且我希望其他类能够看到该列表,但不能 设置 我可以申报

    public class SomeClass()
    {
        public List<string> SomeList { get; }
    }
    

    这将允许另一个类访问somelist,而不设置它。

    但是,尽管调用类不能 设置 列表,它可以添加或删除元素。我该如何预防?我想我可以使用一个字段并返回列表的副本,而不是使用一个属性,但这感觉不太对。

    (这应该很简单,但我一定错过了什么……)

    4 回复  |  直到 8 年前
        1
  •  13
  •   Anon.    16 年前

    您将无法使用自动属性。

    public class SomeClass()
    {
        private List<string> someList;
        public IList<string> SomeList { 
            get { return someList.AsReadOnly(); }
        }
    }
    
        2
  •  4
  •   Gavin Miller    16 年前

    您将希望将列表作为 ReadOnly list .您可以使用以下代码执行此操作:

    using System.Collections.ObjectModel;
    
    public ReadOnlyCollection<string> GetList() {
        return SomeList.AsReadOnly();
    }
    
        3
  •  2
  •   Jay    8 年前

    返回 IEnumerable<string> ,这是不变的。getter应该如下所示:

    public IEnumerable<string> SomeList
    {
       get
       {
          foreach(string s in someList) yield return s; // excuse my inline style here, zealots
          yield break;
       }
    }
    
        4
  •  0
  •   Russ Cam    16 年前
    public class SomeClass()
    {
        private List<string> _someList = new List<string>();
    
        public IList<string> SomeList 
        { 
             get { return _someList.AsReadOnly(); } 
        }
    }