从会话对象获取属性时出现NullReferenceException

时间:2013-12-10 12:52:20

标签: asp.net nullreferenceexception

我创建了一个名为Examination的类,在此类中我有一个名为Get Question()的方法,take exam当我创建Examination的对象并运行时应用程序会出现以下错误。

NullReferenceException: Object reference not set to an instance of an object.

Source Error: 


Line 18:         Examination e = (Examination)Session["questions"];
Line 19:         // display data
Line 20:         lblSubject.Text = e.sname;
Line 21:         lblQno.Text = e.curpos + 1 + "/" + e.SIZE;
Line 22:         lblCtime.Text = DateTime.Now.ToString();

1 个答案:

答案 0 :(得分:3)

最有可能Session["questions"]不包含值,并返回null。将null强制转换为引用类型是完全有效的,但是当您尝试访问它的属性时会发生异常。

您应该测试它是否为空,例如:

Examination e = (Examination)Session["questions"];
if (e == null)
{
    lblSubject.Text = "Your session has expired";
}

(如果我错了,e实际上包含对Examination对象的引用,那么它是lblSubject null}