检查对象是否为空

本文关键字:是否 对象 检查 | 更新日期: 2023-09-27 18:03:17

我想检查User是否存在于数据库中,我取一个User对象并检查它是否为空。但问题是,在我的代码中如果user不存在于我们的数据库它返回以下异常,

对象引用未设置为对象的实例。

我知道当我们的数据库中没有这样的用户时,会发生这个错误。我想知道这个用户对象(我想返回null或not)是否为空。

My Part of Code

  if(newsManager.GetUserUsingEmail(User.Email).Email != null) //If user doesn't exists this come the above mentioned exception
    {
        //User Exists
    }
    else
    {
       //User Doesn't exists
    }

如何解决?

检查对象是否为空

null引用异常可能是由于您试图访问从GetUserUsingEmail方法返回的用户的Email属性。你应该先测试返回值是否为空,然后再尝试访问它的属性。

var user = newsManager.GetUserUsingEmail(User.Email);
if (user != null)
{
     // user exists
}
else
{
    // user does not exist
}

如果newsManager.GetUserUsingEmail(User.Email)返回null,那么您将同意尝试调用.Email应该给您Object reference not set to an instance of an object.错误,对吗?

正如评论中所建议的,如果您的条件确实只是检查用户是否存在,那么只需执行以下操作:

if(newsManager.GetUserUsingEmail(User.Email) != null) //If user doesn't exists this come the above mentioned exception
{
    //User Exists
}
else
{
    //User Doesn't exists
}

如果,如你的代码所示,你的意图是真正进入if块,只有当你有一个有效的Email值为一个有效的用户,那么你可以这样做:

var user = newsManager.GetUserUsingEmail(User.Email);
if(user != null && !string.IsNullOrEmpty(user.Email))
{
    //User Exists and has a valid email
}
else
{
    //User Doesn't exists or doesn't have a valid email.
}

不能从null获取属性。检查对象!= null:

if(newsManager.GetUserUsingEmail(User.Email) != null) //If user doesn't exists this come the above mentioned exception
    {
        //User Exists
    }
    else
    {
       //User Doesn't exists
    }

在c# 6.0中你可以使用安全导航操作符(?.):

 if(newsManager.GetUserUsingEmail(User.Email)?.Email != null) //If user doesn't exists this come the above mentioned exception
    {
        //User Exists
    }
    else
    {
       //User Doesn't exists
    }