代码之家  ›  专栏  ›  技术社区  ›  user1899020

如何使具有List<>成员的类不可变?

  •  3
  • user1899020  · 技术社区  · 10 年前

    例如

    class School
    {
        public List<Student> Students {get; private set;}
    }
    

    在这里 School 不是不可变的,因为getter Students 是可变集合。如何使类不可变?

    2 回复  |  直到 10 年前
        1
  •  5
  •   poke    10 年前

    你可以直接暴露 an immutable list 而是:

    class School
    {
        private readonly List<Student> _students = new List<Student>();
    
        public ReadOnlyCollection<Student> Students
        {
            get { return _students.AsReadOnly(); }
        }
    }
    

    当然,这样做对 Student 对象,因此是完全不可变的 大学生 对象需要是不可变的。

        2
  •  4
  •   James    10 年前

    只需将支持字段设置为私有字段,并使公共属性的getter返回列表的只读版本。

    class School
    {
        private List<Student> students;
    
        public ReadOnlyCollection<Student> Students
        {
            get
            {
                return this.students.AsReadOnly()
            }
    
            private set;
        }
    }