如果对象为空,我想防止对其进行进一步处理。

在下面的代码中,我检查对象是否为空:

if (!data.Equals(null))

and

if (data != null)

然而,我在datlist . add (data)收到一个NullReferenceException。如果对象为空,它甚至不应该输入If语句!

因此,我在问这是否是检查对象是否为空的正确方法:

public List<Object> dataList;
public  bool AddData(ref Object data)
    bool success = false;
    try
    {
        // I've also used "if (data != null)" which hasn't worked either
        if (!data.Equals(null))
        {
           //NullReferenceException occurs here ...
           dataList.Add(data);
           success = doOtherStuff(data);
        }
    }
    catch (Exception e)
    {
        throw new Exception(e.ToString());
    }
    return success;
}

如果这是检查对象是否为空的正确方法,那么我做错了什么(如何防止对对象进行进一步处理以避免NullReferenceException)?


当前回答

从c# 9开始你就可以做到

if (obj is null) { ... }

非空用

if (obj is not null) { ... }

如果需要重写此行为,请相应使用==和!=。

其他回答

从c# 8开始,你可以使用'empty'属性模式(带模式匹配)来确保对象不为空:

if (obj is { })
{
    // 'obj' is not null here
}

这种方法意味着“如果对象引用了某个对象的实例”(即它不是空的)。

你可以把它看作是:if (obj is null)....的对立面当对象没有引用某个对象的实例时,返回true。

有关c# 8.0模式的更多信息,请阅读这里。

你可以像下面这样试试

public List<Object> dataList;
public  bool AddData(ref Object data)
bool success = false;
try
{
    if (data != null)
    {
       dataList.Add(data);
       success = doOtherStuff(data);
    }
}
catch (Exception e)
{
    throw new Exception(e.ToString());
}
return success;

}

在。net 6中有一个一行程序

ExampleMethod(null);

void ExampleMethod(object param)
{
    ArgumentNullException.ThrowIfNull(param);
    // Do something
}
public bool IsVisible(object ClaimCount)
    {
        bool flag = true;
        #region || HIDE COLUMNS ON CONDITION BASIS
        if (!String.IsNullOrEmpty(Convert.ToString(ClaimCount)))
        {
            Int32 ClaimCnt = Convert.ToInt32(ClaimCount);
            if (ClaimCnt == 1)
            {
                flag = false;
            }
        }
        #endregion
        return flag;
    }

使用c#9(2020),您现在可以使用以下代码检查参数为空:

if (name is null) { }

if (name is not null) { }

你可以在这里获得更多信息