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

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

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;

其他回答

不,你应该用!=。如果数据实际上是空的,那么你的程序将会因为试图在null上调用Equals方法而导致NullReferenceException崩溃。还要意识到,如果你特别想检查引用是否相等,你应该使用Object。方法,因为你永远不知道Equals是如何实现的。

你的程序崩溃是因为dataList是空的,因为你从来没有初始化它。

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

if (obj is null) { ... }

非空用

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

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

  public static bool isnull(object T)
  {
      return T == null ? true : false;
  }

use:

isnull(object.check.it)

有条件的使用:

isnull(object.check.it) ? DoWhenItsTrue : DoWhenItsFalse;

更新(另一种方式)更新于2017年8月31日和2021年1月25日。谢谢你的评论。

public static bool IsNull(object T)
{
    return (bool)T ? true : false;
}

骨干示范

为了记录,你在Github上有我的代码,去看看吧: https://github.com/j0rt3g4/ValidateNull PS:这一点是特别为你准备的,Chayim Friedman,不要使用测试软件,假设这一切都是真的。等待最终版本或使用您自己的环境进行测试,然后在没有任何文档或演示的情况下假设真正的beta软件。

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

/// <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);
}

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

 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 //
   }