假设我有 2 页“A”和“B”。我在“A”中设置了一个会话变量,该变量在“B”页面的 page_load 函数中使用:
if (!string.IsNullOrEmpty(Session["x"].ToString()))
{
}
并根据该会话变量的值执行适当的操作,但如果我首先打开页面“B”,则会出现错误:
Object reference not set to an instance of an object.
我如何预先设置这个对象的实例?
假设我有 2 页“A”和“B”。我在“A”中设置了一个会话变量,该变量在“B”页面的 page_load 函数中使用:
if (!string.IsNullOrEmpty(Session["x"].ToString()))
{
}
并根据该会话变量的值执行适当的操作,但如果我首先打开页面“B”,则会出现错误:
Object reference not set to an instance of an object.
我如何预先设置这个对象的实例?
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) {}
你正在使用Session["x"].ToString()
when SessionX
is null 这就是你得到的原因null exception
所以你应该检查那Session["x"]
不应该是null
if(Session["x"] != null )
{
// your code
}