简体   繁体   English

为什么LinkedListNode Next属性是只读的?

[英]Why is LinkedListNode Next property readonly?

I've been working on LeetCode problems using Visual Studio IDE and have noticed an issue when trying to set a linkedlistnode's next value to a new node, which is that 'property or indexer ......Next cannot be assigned to -- it is read only' . 我一直在使用Visual Studio IDE处理LeetCode问题,并且在尝试将LinkedListNode的下一个值设置为新节点时注意到一个问题,即“属性或索引器...下一个不能分配给-它是只读的” I can assign a node's next to a node, but cannot assign a node to a node's next. 我可以将节点的下一个分配给节点,但是不能将节点的下一个分配给节点。 Why is this the case with .NET? .NET为什么会这样?

var l1Value = l1 == null ? 0 : l1.Value;
var l2Value = l2 == null ? 0 : l2.Value;
var newNode = new LinkedListNode<int>((l1Value + l2Value + overflow) % 10);
start.Next = newNode; <------ red squiggly
start = start.Next; <------ no red squiggly

You should use AddBefore / AddAfter / AddFirst / AddLast methods on LinkedList to add elements to your list. 您应该在LinkedList上使用AddBefore / AddAfter / AddFirst / AddLast方法将元素添加到列表中。

I don't know 100% but I assume the API surface does not allow you to modify Next element of a LinkedListNode because that would allow you to end up with weird things like cycles, incomplete lists, etc. Mainly things that make of an inconsistent state. 我不知道100%,但我认为API表面不允许您修改LinkedListNode Next元素,因为这将使您最终遇到怪异的事情,例如循环,不完整的列表等。主要是构成不一致的事物州。 The documentation says LinkedList does not support that: 该文档说LinkedList不支持:

The LinkedList<T> class does not support chaining, splitting, cycles, or other features that can leave the list in an inconsistent state. LinkedList<T>类不支持链接,拆分,循环或其他可能使列表处于不一致状态的功能。 The list remains consistent on a single thread. 该列表在单个线程上保持一致。 The only multithreaded scenario supported by LinkedList<T> is multithreaded read operations. LinkedList<T>支持的唯一多线程方案是多线程读取操作。

Instead of exposing the low level Next / Previous properties with setters the authors decided it's better to provide methods to accomplish the common insertion/deletion operations and make sure all the right things happen. 作者认为,与其提供低级的Next / Previous属性(而不是setter),不如提供一种方法来完成常见的插入/删除操作并确保所有正确的事情发生,这是更好的选择。 Eg they make sure both Next and Previous get updated on every insert/delete. 例如,他们确保“ Next和“ Previous在每个插入/删除操作中均得到更新。 If they allowed you to modify Next or Previous directly it wouldn't be possible to make sure both are always updated when necessary. 如果他们允许您直接修改“ Next或“ Previous ,则无法确保在必要时始终都对它们进行更新。 You can still accomplish what you need but they limited the possibility of bugs when people implement these operations themselves. 您仍然可以完成所需的操作,但是当人们自己执行这些操作时,它们会限制发生错误的可能性。

Next property has only getter that returns the next item from LinkedListNode . Next属性只有getter可以从LinkedListNode返回下一个项目。

I think you are looking for start.List.AddLast(newNode) . 我认为您正在寻找start.List.AddLast(newNode)

Hope helps, 希望有帮助,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM