1

假设我有 2 页“A”和“B”。我在“A”中设置了一个会话变量,该变量在“B”页面的 page_load 函数中使用:

 if (!string.IsNullOrEmpty(Session["x"].ToString()))
 {
 }

并根据该会话变量的值执行适当的操作,但如果我首先打开页面“B”,则会出现错误:

 Object reference not set to an instance of an object.

我如何预先设置这个对象的实例?

4

2 回答 2

1

IsNullOrEmpty在执行操作和评估传递给的参数之前,您会遇到异常IsNullOrEmpty。您将通过调用ToString()ifSession["x"]Session["x"]null 得到异常。所以在调用之前你会得到异常IsNullOrEmpty

改变

if (!string.IsNullOrEmpty(Session["x"].ToString())) {} 

To

if(Session["x"] != null && Session["x"].ToString() != string.Empty) {} 
于 2013-04-06T21:00:56.450 回答
1

你正在使用Session["x"].ToString()when SessionXis null 这就是你得到的原因null exception 所以你应该检查那Session["x"]不应该是null

if(Session["x"] != null )
{
  // your code
}
于 2013-04-06T21:01:34.687 回答