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

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

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# 6有单值空检查:)

之前:

if (points != null) {
    var next = points.FirstOrDefault();
    if (next != null && next.X != null) return next.X;
}   
return -1;

后:

var bestValue = points?.FirstOrDefault()?.X ?? -1;

其他回答

以下是我使用的一些扩展:

/// <summary>
/// Extensions to the object class
/// </summary>
public static class ObjectExtensions
{
    /// <summary>
    /// True if the object is null, else false
    /// </summary>
    public static bool IsNull(this object input) => input is null;

    /// <summary>
    /// False if the object is null, else true
    /// </summary>
    public static bool NotNull(this object input) => !IsNull(input);
}

你的dataList是空的,因为它还没有被实例化,从你发布的代码判断。

Try:

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

你可以像下面这样试试

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;

}

除了@何塞·奥尔特加的回答, 采用拓延法效果较好

 public static bool IsNull(this object T)
     {
        return T == null;
     } 

然后对所有对象使用IsNull方法,例如:

object foo = new object(); //or any object from any class
if (foo.IsNull())
   {
     // blah blah //
   }

c# 6有单值空检查:)

之前:

if (points != null) {
    var next = points.FirstOrDefault();
    if (next != null && next.X != null) return next.X;
}   
return -1;

后:

var bestValue = points?.FirstOrDefault()?.X ?? -1;