Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/271.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#.NET检查对象是否为空_C#_Asp.net - Fatal编程技术网

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

C#.NET检查对象是否为空,c#,asp.net,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 } Find方法(使用ORM-Dapper)。对此进行了单元测试,我相信这种方法没有问题 public Object Find(string id)

我这样做对吗?我想知道它失败的可能原因

Object obj = Find(id); //returns the object. if not found, returns null
if (!Object.ReferenceEquals(obj, null))
{
     //do stuff
}
else
{
     //do stuff
}
Find方法(使用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;
}
公共对象查找(字符串id)
{
var result=this.db.QueryMultiple(“GetDetails”,new{Id=Id},commandType:commandType.StoredProcedure);
var obj=result.Read().SingleOrDefault();
返回obj;
}
试试这个:

   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
   }

我会做以下的事情。为什么不必要地否定空检查

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
}

看起来不错,但您也可以使用
obj!=null
obj的类型是什么?它是引用类型还是值类型?它是引用类型。它在
obj上也会失败=空
您能用
Find
方法的代码更新您的问题吗?还有,
id
的值是多少,这使得
obj=null
失败?如果您知道实际类型,请不要将变量声明为对象。使用显式类型。