是否可以返回调用者无法修改的只读 ObservableCollection?
考虑以下代码:
public ObservableCollection<Message> Messages {
get { return new ObservableCollection<Message>(); }
}
我可以采取什么措施来防止调用者代码添加/删除/更改项目?
编辑:抱歉,大家,我刚刚注意到这是一个骗局,但接受的答案是错误的。
Consider the following code:
public ObservableCollection<Message> Messages {
get { return new ObservableCollection<Message>(); }
}
Is there anything I can do to prevent the caller code from adding/removing/changing items?
EDIT: Sorry, everyone, I just noticed it's a dupe, but the accepted answer is wrong.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用 ReadOnlyObservableCollection
代码会是:
阅读关于ReadOnlyObservableCollection 反模式 我意识到上述方法不是一个好方法,可能会导致微妙的错误。建议的方法是:
What about using ReadOnlyObservableCollection
Code would be:
Having read aboutReadOnlyObservableCollection Anti Pattern I realise the above is the not a good approach and may lead to subtle bugs. The suggested approach is:
为什么需要只读 ObservableCollection。
如果该集合是只读的,则无需观察它。
考虑一个集合
Why do you need a read only ObservableCollection.
If this collection is read only you don't need to observe it.
Consider a Collection<T>
返回一个
ReadOnlyObservableCollection
:Return a
ReadOnlyObservableCollection
instead:如何使用 ReadOnlyObservableCollection< T>
What about to use the ReadOnlyObservableCollection< T >