SWe*_*eko 3 c# properties readonly
我有一个类,它定义了一个只读属性,可以有效地公开一个私有字段,如下所示:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
现在消费者不可能直接管理我的属性,所以代码如aContainer.MyList = new List(); 生成编译时错误.但是,消费者可以完全自由地在他所获得的引用上调用各种方法,因此这是完全有效的代码
Container c = new Container();
Console.WriteLine(c.MyList.Count);
c.MyList.Add(4);
Console.WriteLine(c.MyList.Count);
Run Code Online (Sandbox Code Playgroud)
哪种打败了整个只读概念.
是否有任何理智的解决方法可以让我有一个真正的只读参考属性?
PS我不能只返回列表的副本,因为用户会认为他做了所有必要的更改,但唉...他们将会消失.
不要直接引用您的列表.而是返回一个包裹它的ReadOnlyCollection,或者如果List <>返回类型是一成不变的,则返回列表的副本.他们可以做任何他们想要的副本而不影响原件.