1

我已经“继承”了一个包含以下代码行的项目:

        objLibPharmacy.UserId = Guid.Parse(Session["GroupId"].ToString());

当我运行调试器时,我收到一条错误消息:

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web 
request. Please review the stack trace for more information about the error and where it 
originated in the code. 

部分堆栈跟踪如下:

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

UserControl_wuc_Pharmacy.bindPharmacyPopUp()

bindPharmacyPopUp 如下:

  private void bindPharmacyPopUp()
{
    /******************Bind Pharmacy Popup*********************/
    objLibPharmacy = new LibPharmacy();
    objLibPharmacy.PharmacyId = 0;
    objLibPharmacy.UserId = Guid.Parse(Session["GroupId"].ToString());
    objclsPharmacy = new clsPharmacy();
    objDs = objclsPharmacy.GetPharmacy(objLibPharmacy);
    string strFilter = "";
    if (objDs != null)
    {
        if (txtSearchPharmacy.Text != "")
            strFilter = "PharmacyName like '%" + txtSearchPharmacy.Text + "%'";
        DataView dv = objDs.Tables[0].DefaultView;
        if (strFilter != "")
            dv.RowFilter = strFilter;
        Utility.bindGridview(dv.ToTable(), gvPharmacyList);
        Utility.bindDDL(objDs.Tables[1], ddlPharmacyDetail, "Pharmacy");
        //ViewState["PharmacyTable"] = objDs.Tables[0];
    }

    /*********************************************************/
}

是什么导致空引用?如何处理此类空引用以使调试无错误地运行?

4

3 回答 3

10

如果Session["GroupId"]为空,就会发生这种情况。

在尝试使用它之前,您需要检查它。

于 2013-08-08T17:34:28.690 回答
4

顾名思义,当您尝试对未初始化或已取消引用的对象执行操作时,会发生Null Reference Exception 。在这种情况下,您正在调用.ToString()Session["GroupId"]它可能尚未初始化。

最好的办法是在访问之前初始化 GroupId 会话变量。作为一种解决方法,如果变量为 null ,您可以跳过解析:

if (Session["GroupId"] != null)
{
    objLibPharmacy.UserId = Guid.Parse(Session["GroupId"].ToString());
}
于 2013-08-08T17:41:08.553 回答
0

你可以试试这个Guid.TryParse方法:

Guid userId;
if (Guid.TryParse(Session["GroupId"].ToString(), out userId))
   objLibPharmacy.UserId = userId;
于 2013-08-08T17:48:44.170 回答