【问题标题】:Why is LinkedListNode class immutable?为什么 LinkedListNode 类是不可变的?
【发布时间】:2014-08-23 18:01:17
【问题描述】:

我很想知道为什么 LinkedListNode 类公开的所有属性(下一个、上一个、值等)都是只读的,即这些属性没有相应的设置器?

我试图解决一个与链表相关的小算法问题,并决定使用 .Net 内置的 LinkedList 类。但由于 LinkedListNode 类属性的只读行为,我无法覆盖这些值或更改任何给定节点的“Next”指针。

谢谢

【问题讨论】:

  • 我能够更改 Value 属性,即使文档没有表明 Value 是可设置的
  • @AndrewWhitaker:它表明它是可设置的:marker.to/2iMfJ5 虽然该属性的摘要描述具有误导性。

标签: c# .net linked-list


【解决方案1】:

Value确实有一个setter,声明是public T Value { get; set; }。

Next 和 Previous 上缺少设置器会阻止您将链表转换为 LinkedList 方法无法处理的树或其他拓扑。

The LinkedList class does not support chaining, splitting, cycles, or other features that can leave the list in an inconsistent state.

您可以使用列表的方法来更改这些属性,例如 AddBefore,这些方法保留了每个 LinkedListNode 仅属于一个列表的不变量,node.Next.Previous 始终指向 node,并且没有循环等。

【讨论】:

  • 这可能是您无法更改Next 或Previous 属性的原因。更改值不会将列表更改为树。
【解决方案2】:

Next/Previous 是只读的,以确保您不会弄乱列表结构。你必须使用LinkedList<T> 方法来修改列表,它们会确保你不会得到不正确的状态。让您更改引用将使其成为可能。

虽然MSDN states,那个Value是不可设置的,但是如果你看LinkedListNode<T> source code,你会发现实际上定义了一个setter!

// Note following class is not serializable since we customized the serialization of LinkedList. 
[System.Runtime.InteropServices.ComVisible(false)] 
public sealed class LinkedListNode<T> {
    internal LinkedList<T> list;
    internal LinkedListNode<T> next;
    internal LinkedListNode<T> prev;
    internal T item;

    public LinkedListNode( T value) {
        this.item = value;
    }

    internal LinkedListNode(LinkedList<T> list, T value) {
        this.list = list;
        this.item = value;
    }

    public LinkedList<T> List {
        get { return list;}
    }

    public LinkedListNode<T> Next {
        get { return next == null || next == list.head? null: next;}
    }

    public LinkedListNode<T> Previous {
        get { return prev == null || this == list.head? null: prev;}
    }

    public T Value {
        get { return item;}
        set { item = value;}
    }

    internal void Invalidate() {
        list = null;
        next = null;
        prev = null;
    }           
}  

所以你应该可以改变这个值。

【讨论】:

  • 哦,这和LinkedListNode(T)页面不一致:msdn.microsoft.com/en-us/library/ahf4c754(v=vs.110).aspx。应该是Gets or sets the value contained in the node。
  • 文档可能在某些地方与实现的内容不一致(特别是在属性及其 getter 和 setter 周围)。这只是其中一种情况。
猜你喜欢
  • 2011-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-28
  • 1970-01-01
  • 2015-05-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多