在 C# 中检查空值时出现问题

本文关键字:问题 空值 检查 | 更新日期: 2023-09-27 17:55:39

>我有以下方法:

void setTexts()
{
    if (queueIn != null)
    {
        queueIn.text = countIn.ToString();
    }
    if (queueOut != null)
    {
        queueOut.text = waitingForPickup.ToString();
    }
}

如果 queueIn 为空,我希望它什么都不做,但我不断收到一个空引用异常,说 queueIn 为空。当 queueIn 为空时,为什么它会进入 if 块?

编辑:当我添加Debug.Log检查时,问题消失了,所以它可能没有保存前十几次或其他东西。感谢您的建议!我对 C# 很陌生。

在 C# 中检查空值时出现问题

您需要检查所有对象尊重点。在这种情况下,countIn可能是您的罪犯。

以下是删除异常的可能解决方案。

void setTexts(){
    if (queueIn != null && countIn != null) {
        queueIn.text = countIn.ToString ();
    }
    if (queueOut != null && waitingForPickup != null){
        queueOut.text = waitingForPickup.ToString();
    }
}

您正在countInwaitingForPickup上调用ToString() - 您也需要检查它们。 例如:

void setTexts(){
    if (queueIn != null && countIn != null) {
        queueIn.text = countIn.ToString();
    }
    if (queueOut != null && waitingForPickup != null) {
        queueOut.text = waitingForPickup.ToString();
    }
}