如何在 C# 中重写 List.IsReadOnly
我试图从 List 派生并有选择地打开和关闭 IsReadOnly 属性。 我希望添加/删除/[] 函数能够尊重这个属性,但他们没有。 这样做的正确方法是什么?
我的派生类有一些附加属性,因此不幸的是我不能将列表包装在 ReadOnlyCollection 中。
I'm trying to derive from List and selectively turn the IsReadOnly property on and off. I was hoping that the Add/Remove/[] functions would honor this property, but they don't.
What's the right way of doing this?
My derived class has some additional properties, so I can't unfortunately just wrap the list in ReadOnlyCollection.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在这种情况下使用封装而不是继承。
您应该让您的类实现 IList,并拥有一个私有 List。 多变的。
您可以传递任何您想要的函数,但也可以完全覆盖它们、更改行为等。这为您提供了完全的控制权(代价是有许多方法除了调用 this.List.method(...) 之外什么都不做) 。
一般来说,我认为在任何情况下从 BCL 集合类继承都不是一个好主意。 我更喜欢将它们作为我班级内部的实现细节。
Use encapsulation instead of inheritance in this case.
You should just make your class implement IList<T>, and have a private List<T> variable.
You can pass through any functions you wish, but also can completely override them, change behavior, etc. This gives you complete control (at the expense of having many methods that does nothing but call this.List.method(...) ).
In general, I don't think it's a good idea to inherit from the BCL collection classes in any case. I prefer to make them an implementation detail internal in my class.
列表根据定义是可变类型。 没有办法使其只读。
如果您正在创建派生类,您可能应该实现 IList; 直接而不是子类化 List反正。 这将使您能够完全控制实施,如果您愿意,您可以将其设置为只读。
List<T> is by definition a mutable type. There's no way to make it read-only.
If you're making a derived class, you should probably be implementing IList<T> directly rather than subclassing List<T> anyway. This will give you full control over the implementation, allowing you to make it read-only if you wish.
您可以在列表上调用“AsReadOnly”方法,该方法应返回一个 IList 实例,该实例应遵守它是...错误...只读的。
...好吧,我刚刚读了你的最后一句话,我的错。 在这种情况下,您可能只想实现 IList 接口或任何朋友,并将大部分接口路由到您内部保留的列表。 然后你就可以构建这个行为。 即便如此,我也会采用类似的模式,提供一些“AsReadOnly”方法,明确为您提供只读的内容。
You could call the "AsReadOnly" method on list which should return to you an IList instance that should honor that it is...err...read-only.
...OK, I just read your last sentence, my bad. In which case maybe you just want to implement the IList interface or any friend and just route most of the interface to a list you keep internally. Then you can build this behaviour. Even so, I would do a similar pattern, provide some "AsReadOnly" method that explicitly gives you something that is read-only.