C#.NET检查对象是否为null

use*_*ser 5 c# asp.net

我这样做是对的吗?我有兴趣知道它失败的可能原因吗?

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

查找方法(使用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;
}
Run Code Online (Sandbox Code Playgroud)

eka*_*kad 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
   }
Run Code Online (Sandbox Code Playgroud)