C#通过引用修改只读字段



我来自C++,非常怀念C#中的"const"。

我已经在我的代码中找到了一个讨厌的错误,考虑一下:

class MyClass {
    BitArray myFlags { get; private set; } // this should not be able to be manipulated from outside
    // ... constructor here creating the BitArray ...
}
// ...
MyClass foo = new MyClass();
BitArray bar = foo.myFlags;
bar.SetAll(false); // circumvents encapsulation eventually putting the class in inconsitent state

用户可以毫无问题地更改我的对象的状态。如何安全地公开类的成员,而不让用户有机会操纵我的对象的状态?当提供对该成员的公共(读取)访问时,我是否必须".clone()"每个基于引用的成员(所以基本上是所有成员)?

我想要实现的是适当的封装。当用户创建我的类的实例并读取成员时,我希望保护该成员不被写入,除非它也有公共setter。

C#提供ReadOnlyCollection作为不可变集合的选项。

希望它能有所帮助!

最新更新