1

我对班级成员的可访问性有疑问。

我有 3 个类一起工作,需要完全访问彼此的属性。A类、B类、C类

但是 classA 在其他地方使用,该类的所有用户都应该只有对所有结构的读取权限!

这些类看起来像这样:

public class classA
{
    public ClassB B { get ; }
    ...
}

public class classB
{
    ClassC C { get ;  set ; }
    ...
}

public class classC
{
    ArrayList L { get ;  set ; }
    ...
}

如何管理 classA 和 classB 对 classC 具有完全访问权限,但 class A 的所有用户都不能修改里面的任何内容?

例如,这仍然是可能的:(

classA A = new A();
A.B.C.L.Add( something);

即使 AB 由于缺少集合而无法修改。

我看到的一种可能性是,属性 AB 返回结构的深层副本,因此修改 AB 不会影响源结构,但我对此并不满意。

有没有办法在编译时检查写访问,就像我使用“只读”或省略“设置”一样?

4

1 回答 1

2

The easiest approach is to provide a read only proxy for accessing the data in B - just like the ReadOnlyCollection, which wraps a regular collection, providing a read only version of the same interface. So you wouldn't return a classB, but a ReadOnlyB.

Alternatively this read only interface could be implemented in classA to allow more "direct" access to the data.

You could possibly then put A,B,C into a different assembly and make B,C internal so that the client can't see them.

于 2013-04-07T16:02:09.227 回答