2

I am trying to delete a Node from a linked list. Below is the code I have tried.

public class Node : IDisposable
{
    public int Value { get; set; }
    public Node Next { get; set; }

    public Node(int value)
    {
        this.Value = value;
    }

    public void Dispose()
    {
        Dispose(true);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            Next.Dispose();
        }
    }
}

public class LinkedList
{
    Node head;
    public void CreateList()
    {
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);

        head = node1;
        node1.Next = node2;
        node2.Next = node3;
    }

    public void DeleteLastItem()
    {
            Node prevNode = head;
            Node nextNode = head;

            while (nextNode.Next != null)
            {
                prevNode = nextNode;
                nextNode = nextNode.Next;
            }
            prevNode.Next = null;
            nextNode.Dispose();
    }
}

I wanted to dispose the nextNode (which is nothing but the last node. And it will not be part of the Linked List).

When I try above code, I am getting below exception:

Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.

How can I proceed here ? How can I dispose a Node object?

4

3 回答 3

4

在您的Dispose(bool)方法中,您只能处置下一个节点(如果有的话)。在尝试之前检查空引用:

protected virtual void Dispose(bool disposing) {
  if (disposing) {
    if (Next != null) {
      Next.Dispose();
    }
  }
}
于 2013-04-24T14:23:55.890 回答
3

我想您应该在调用 Dispose 之前简单地检查 Next 是否不为空。

当在任何节点上调用 Dispose 方法时,您手动调用下一个,这样您将到达最后一个,Next 属性将为空,因此您会收到此异常。

考虑到您提供的代码,我不明白您为什么需要您的节点是一次性的。仅当您使用非托管资源时才需要,这在您提供的代码中不是这种情况(但也许您为问题简化了它)。

于 2013-04-24T14:26:19.827 回答
1

在您的 Dispose 逻辑中,检查 NULL:

public class Node : IDisposable
{
    public int Value { get; set; }
    public Node Next { get; set; }

    public Node(int value)
    {
        this.Value = value;
    }

    public void Dispose()
    {
        Dispose(true);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (Next != null) // <-- new code here
            {
                Next.Dispose();
            }                 
        }
    }
}
于 2013-04-24T14:26:39.013 回答