LinkedList 的只读包装。怎么做?
.NET v2
当 List 有一个非常有用的(4 me)方法 AsReadOnly() LinkedList没有这样的方法。
有没有一种方法可以“快速”连接内部LinkedList以仅从外部代码读取?
.NET v2
When the List has a very useful (4 me) method AsReadOnly()
the LinkedList does not have such a method.
Is there a way to "quickly" interface an internal LinkedList to read only from the external code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为什么不直接返回
IEnumerable
?如果您只想让用户枚举列表而不修改它*,IEnumerable 是显而易见的选择。如果你想拥有 LinkedList 接口的只读接口,你可以包装 LinkedList,将只读方法转发到包装列表并拒绝任何更改。
*)请记住,在引用类型集合的情况下,ReadOnlyCollection 和 IEnumerable 都不会阻止调用者更改对象的状态。如果对象也应该是只读的,则需要将其实现为对象类型的一部分。
Why not just return a
IEnumerable<T>
? If you just want to let users enumerate the list without modifying it*, IEnumerable is the obvious choice.If you want to have a read only interface of the LinkedList interface, you can wrap LinkedList, forward read only methods to the wrapped list and deny any changes.
*) Keep in mind that neither ReadOnlyCollection not IEnumerable will prevent callers to change state of objects in case of a collection of reference types. If the objects should be read only as well, you need to implement this as part of their type.
ReadOnlyCollection
将IList
作为构造函数的参数。LinkedList
未实现此接口。List
具有一个构造函数重载,该重载采用IEnumerable
作为参数,并且LinkedList
实现此接口。因此,以下内容应该有效:它使用
List
实例将项目携带到ReadOnlyCollection
构造函数中。ReadOnlyCollection<T>
takes anIList<T>
as argument to the constructor.LinkedList<T>
does not implement this interface.List<T>
has a constructor overload that takes anIEnumerable<T>
as argument, andLinkedList<T>
implements this interface. So the following should work:It uses an instance of
List<T>
to carry the items into theReadOnlyCollection<T>
constructor.#1 修复链接列表
#2 将其实例包装在 ReadOnlyCollection 中
#1 Fix the Linked List
#2 Wraps its instances in ReadOnlyCollection
LinkedList
没有实现IList
所以简而言之,没有办法快速做到这一点。如果将 LinkedList 转换为列表,您可能会失去所需的功能。LinkedList
不为您提供任何子类化功能,因此您需要编写自己的。我想下一个请求是“你能告诉我该怎么做吗”LinkedList<T>
doesn't implementIList
so in short, no there is no way of quickly doing it. If you cast your LinkedList to a List you will probably lose the functionality you require.LinkedList<T>
doesn't offer you anything for subclassing so you'll need to write your own. I imagine the next request is "can you show me how to do that"