为什么我在测试null时收到此NullReferenceException错误?

时间:2012-03-15 13:48:51

标签: c# asp.net web-services

我在以下代码行收到错误:对象引用未设置为对象的实例。

if (Session["AutoCompleteCustomersPhone"] != null)

完整的代码块:

if (Session["AutoCompleteCustomersPhone"] != null)
    earchCustomerPhone = true;
else
{
    searchCustomerPhone =
        bool.Parse(Session["AutoCompleteCustomersPhone"].ToString());
}

为什么,在测试null时,我收到此错误?

enter image description here

2 个答案:

答案 0 :(得分:10)

您的if声明是错误的。如果 为空,则尝试使用该值。

改变这个:

if (Session["AutoCompleteCustomersPhone"] != null)

到此:

if (Session["AutoCompleteCustomersPhone"] == null)

我首先解决了这个问题,看看是否能解决问题。

来自特定行的异常可能是因为:

  • Session变量为null - 您可以在调试器中验证这一点。
  • 您编译的代码与您用于调试的源代码不同。尝试清洁和重建。

答案 1 :(得分:4)

因为sessionn对象本身为null

我认为您正在使用webservice,这就是会话为空的原因*

如果您在网络服务中使用会话,请查看此文章: Using Session State in a Web Service