我有一个类,它定义了一个有效公开私有字段的只读属性,如下所示:
public class Container
{
private List<int> _myList;
public List<int> MyList
{
get { return _myList;}
}
public Container() : base ()
{
_myList = new List<int>();
}
// some method that need to access _myList
public SomeMethod(int x)
{
_myList.Add(x);
}
}
现在消费者不可能直接管理我的财产,所以像 aContainer.MyList = new List(); 这样的代码 生成编译时错误。但是,消费者完全可以自由地调用他得到的引用的各种方法,所以这是完全有效的代码
Container c = new Container();
Console.WriteLine(c.MyList.Count);
c.MyList.Add(4);
Console.WriteLine(c.MyList.Count);
哪种破坏了整个只读概念。
是否有任何健全的解决方法可以让我拥有真正的只读参考属性?
PS我不能只返回列表的副本,因为这样用户会认为他做了所有必要的更改,但是唉......他们会消失的。