条件==空

问题描述 投票:0回答:1

大家好,我有这样的代码的情况

LogBase o = null;
lock (_logQueue)
{
    o = _logQueue.Dequeue();
}
if (o == null) continue;

try
{
    switch (o.DataType)
    {
        case LogType.INFO:
            Log(o);
            break;
        case LogType.ERROR:
            LogException(o);
            break;
        default:
            break;
    }
}

总是显示消息“不能为空值”,我想我需要更改条件 o == null

我不知道有什么其他方法可以替换,有人可以帮助我吗?谢谢

c# null nullreferenceexception nullable
1个回答
0
投票

要解决“null”值导致错误消息的问题,您可以在访问

DataType
对象的
o
属性之前添加 null 检查。以下是修改代码的方法:

LogBase o = null;
lock (_logQueue)
{
    o = _logQueue.Dequeue();
}
if (o == null) continue;

try
{
    if (o != null) // Add null check here
    {
        switch (o.DataType)
        {
            case LogType.INFO:
                Log(o);
                break;
            case LogType.ERROR:
                LogException(o);
                break;
            default:
                break;
        }
    }
}

通过添加 null 检查

if (o != null)
,您可以确保仅在
DataType
不为 null 时才尝试访问
o
属性,从而避免出现错误消息。

© www.soinside.com 2019 - 2024. All rights reserved.