【问题标题】:I am getting a NullReferenceException but the object is not null [duplicate]我收到 NullReferenceException 但对象不为空 [重复]
【发布时间】:2017-02-02 01:17:23
【问题描述】:

所以我的代码基本上建立了一个链表。每个票证对象要么存储对另一个票证对象的引用,要么存储为空。 .getNext() 方法获取对列表中下一个对象的引用。 current 是表示列表开头的对象,while 循环遍历列表更改 current 直到条件更改。最后,它将 current 设置为作为参数传递的 Ticket。

public void AddLowPTicket(Ticket ti) // doesnt check if front == null because AddTicket already does
{
    Ticket current = front;
    while(current.getPrio() == Priority.High && current != null) // cycles/skips through the list as long as Priority == High.
    {
        current = current.getNext();
    }
    current.Print(); // *THIS WORKS*
    while(current != null && current.getPrio() == Priority.Low) //  *NullReferenceException: Obj ref not set to an instance of an obj.*
    {
        current = current.getNext();
    }
    current = ti;
}

这是 Ticket 对象的 Print 方法。它可以很好地打印局部变量,这意味着它们不为空。

public void Print()
{
    Console.WriteLine("{0}\nPriority:{1}", m_description, m_prio == Priority.High ? "High" : "Low");
}

如果 current 不为 null 并且它的变量都不为空,为什么它会崩溃。

【问题讨论】:

  • current.getPrio() == Priority.High && current != null 尝试左右交换。
  • @AlexD:这将如何解决问题? @N.Campos:getPrio() 内部发生了什么
  • 确定它发生在你所说的那条线上吗?看起来它可能发生在第一个while - 这将通过 AlexD 的评论来解决。你的调试器说什么?等待它触发异常并检查相关变量。
  • 做一些断点。看看 current.getPrio() 里面有没有东西
  • @un-lucky 如果只有PriorityHigh 项,while 条件似乎会导致空引用异常,不是吗?

标签: c# nullreferenceexception singly-linked-list


【解决方案1】:

大家好,非常感谢您抽出宝贵时间!我猜它没有正确构建(不知何故?)。添加然后删除一些行然后重建/运行它之后它运行正常!抱歉,再次感谢!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-04
    • 1970-01-01
    • 1970-01-01
    • 2019-01-21
    • 2014-08-30
    • 2016-10-18
    • 1970-01-01
    相关资源
    最近更新 更多