if语句为true但代码不执行C#

时间:2015-03-06 00:30:07

标签: c# if-statement

public bool CheckTheEmail(string email)
    {
        //using (SqlConnection con = new SqlConnection("insQuoteConnectionString"))
        using (SqlConnection con = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["insQuoteConnectionString"].ConnectionString))
        {
            con.Open();

            using (SqlCommand cmd = new SqlCommand("select EmailAddress from AspNetUsers", con))
            {
                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    if (reader != null)
                    {
                        while (reader.Read())
                        {
                            //do something


                           if (reader[0] != null)
                            {
                                if (reader[0] == (email))
                                {
                                    Console.WriteLine("ok");
                                    reader.Close();
                                    con.Close();
                                    return true;
                                }
                            }
                        }
                    }
                    reader.Close();
                }
            }
            con.Close();

        }
        return false;
    }

这句话如果(reader [0] ==(email))显示为true但不执行代码!

if语句返回true(在屏幕截图中显示)但不执行。

enter image description here

1 个答案:

答案 0 :(得分:3)

每当您对某些内容进行比较时,确保他们使用兼容类型是一种很好的做法。在这种情况下,SqlDataReader实际上返回Object,因此您需要在进行比较之前将其强制转换为string。 (我真的很惊讶IntelliSense并没有抱怨它)

public bool CheckTheEmail(string email)
{
    using (SqlConnection con = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["insQuoteConnectionString"].ConnectionString))
    {
        con.Open();

        using (SqlCommand cmd = new SqlCommand("select EmailAddress from AspNetUsers", con))
        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            if (reader == default(SqlDataReader))
            {
                return false;
            }

            while (reader.Read())
            {
                //do something

                if (reader[0] != null && reader[0].ToString() == email)
                {
                    Console.WriteLine("ok");
                    return true;
                }
            }
        }
    }

    return false;
}