例如
class School
{
public List<Student> Students {get; private set;}
}
这里 School
不是不可变的,因为 getter Students
是一个可变集合。如何使类不可变?
最佳答案
你可以公开 an immutable list相反:
class School
{
private readonly List<Student> _students = new List<Student>();
public ReadOnlyCollection<Student> Students
{
get { return _students.AsReadOnly(); }
}
}
当然这样做对 Student
对象没有影响,所以要完全不可变,Student
对象需要是不可变的。
关于c# - 如何使具有 List<> 成员的类不可变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37169470/