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

How to make a class with List<> member immutable?

例如

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

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

您可以改为公开 an immutable list

class School
{
    private readonly List<Student> _students = new List<Student>();

    public ReadOnlyCollection<Student> Students
    {
        get { return _students.AsReadOnly(); }
    }
}

当然这样做对Student对象仍然没有影响,所以要完全不可变,Student对象需要是不可变的。

只需将您的支持字段设为私有字段,并将 public 属性 return 的 getter 设为列表的只读版本。

class School
{
    private List<Student> students;

    public ReadOnlyCollection<Student> Students
    {
        get
        {
            return this.students.AsReadOnly()
        }

        private set;
    }
}