C#.NET如何检查对象是否为空

4

我这么做是正确的吗?我想知道它失败的可能原因是什么?

Object obj = Find(id); //returns the object. if not found, returns null
if (!Object.ReferenceEquals(obj, null))
{
     //do stuff
}
else
{
     //do stuff
}

查找方法(使用ORM Dapper)。 我对此进行了单元测试,我认为这个方法没有问题。

public Object Find(string id)
{
     var result = this.db.QueryMultiple("GetDetails", new { Id = id }, commandType: CommandType.StoredProcedure);
     var obj = result.Read<Object>().SingleOrDefault();
     return obj;
}

5
看起来不错,但你也可以使用 obj != null - p.s.w.g
obj 的类型是什么?它是引用类型还是值类型? - ekad
它是一个引用类型。它也会在 obj!=null 失败。 - user
你能否更新你的问题,并附上“Find”方法的代码?另外,“id”的什么值会导致“obj!= null”失败? - ekad
你尝试过在执行“Find”方法后调试并检查“obj”值吗? - ekad
1
如果您知道实际类型是什么,请不要将变量声明为对象。请使用显式类型。 - sh1rts
2个回答

17

试试这个:

   Object obj = Find(id); //returns the object. if not found, returns null
   if (obj != null)
   {
        //do stuff when obj is not null
   }
   else
   {
        //do stuff when obj is null
   }

0
我会这样做。为什么要不必要地否定空检查?
Object obj = Find(id); //returns the object. if not found, returns null

if (obj == null)
{
        //do stuff when obj is null
}
else
{
        //do stuff when obj is not null
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接