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



例如

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

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

您可以只公开一个不可变列表:

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

当然,这样做对Student对象仍然没有影响,因此要完全不可变,Student对象需要不可变。

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

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

最新更新