为什么我得到“对象引用未设置为对象的实例”

时间:2012-09-13 07:07:03

标签: c# .net

  

可能重复:
  What is a NullReferenceException in .NET?

  

对象引用未设置为对象的实例。

protected void Page_Load(object sender, EventArgs e)
{
   int Role = Convert.ToInt32(Request.QueryString["Role"].ToString());
   try
   {
       if (Role != 3)
       {
           gv_ViewApplicants.Visible = true;
           gv_ViewApplicants_SelectedIndexChanged(this, new EventArgs());
       }
       else
       {
           gv_ViewApplicants.Visible = false;
       }
    }
    catch (NullReferenceException e1)
    { 

    }

 }

4 个答案:

答案 0 :(得分:2)

尝试

int Role = Convert.ToInt32(Request.QueryString["Role"] != null ?
                           Request.QueryString["Role"].ToString() : 
                           "0");

而不是

int Role = Convert.ToInt32(Request.QueryString["Role"].ToString());

如果未传递查询字符串,则需要检查null。

答案 1 :(得分:1)

代码正在尝试访问设置为null的引用类型变量的成员。

请将来源Request.QueryString["Role"]设为空。

答案 2 :(得分:1)

第一件事

int Role = Convert.ToInt32(Request.QueryString [“Role”]。ToString());

此语句在外部尝试,如果它在QueryString为空时崩溃,或者即使Convert.ToInt32方法抛出异常,也不会执行catch块。

您可以尝试此代码

  int number;
  bool result = Int32.TryParse(Request.QueryString["Role"], out number);
  if (result)
  {
    // your implemntation       
  }
  else
  {        
    // your implemntation   
  } 

如果仍然出现此错误,您甚至可以使用Convert.ToString(Request.QueryString [“Role”])。

答案 3 :(得分:0)

你应该从不抓住NullReferenceException

然而,问题似乎在第一行:( try区外的唯一一行)

int Role = Convert.ToInt32(Request.QueryString["Role"].ToString()); 

Request为空或QueryString["Role"]返回null

分享堆栈跟踪以获得更清晰的答案。

相关问题