返回集合为只读 [英] Return collection as read-only
问题描述
我在多线程环境中的对象,保持信息的集合,例如:
I have an object in a multi-threaded environment that maintains a collection of information, e.g.:
public IList<string> Data
{
get
{
return data;
}
}
我现在有返回数据;
包裹一个 ReaderWriterLockSlim
来保护共享冲突的集合。不过,为了以防万一,我想返回集合为只读,这样调用code是无法更改的收集,只有查看的内容已经存在。这是在所有可能的?
I currently have return data;
wrapped by a ReaderWriterLockSlim
to protect the collection from sharing violations. However, to be doubly sure, I'd like to return the collection as read-only, so that the calling code is unable to make changes to the collection, only view what's already there. Is this at all possible?
推荐答案
如果你唯一的目的是让调用code不犯错误,和修改时,只应阅读一切必要的是集返回不支持添加,删除,接口等。为什么不返回的IEnumerable&LT;字符串&GT;
?调用code将不得不投,它们不太可能做不知道他们正在访问属性的内部。
If your only intent is to get calling code to not make a mistake, and modify the collection when it should only be reading all that is necessary is to return an interface which doesn't support Add, Remove, etc.. Why not return IEnumerable<string>
? Calling code would have to cast, which they are unlikely to do without knowing the internals of the property they are accessing.
如果您但是意图是prevent从观察其他线程更新调用code,你将不得不回落到已经提到的解决方案,以执行深或浅拷贝根据您的需要。
If however your intent is to prevent the calling code from observing updates from other threads you'll have to fall back to solutions already mentioned, to perform a deep or shallow copy depending on your need.
这篇关于返回集合为只读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!