重複定義造成未將對象引用設定到對象的執行個體錯誤

來源:互聯網
上載者:User

重複定義造成未將對象引用設定到對象的執行個體錯誤
 
作者:icech 

 

   一般在C#中造成“未將對象引用設定到對象的執行個體”錯誤都是控制項名稱與codebehind裡面的沒有對應,對於初學編程的人,而在編碼中重複定義也會造成這種問題的產生。

    以下是一個例子:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace weste
{
 public class study : System.Web.UI.Page
 {
  public string[] c;

  private void Page_Load(object sender, System.EventArgs e)
  {
   aaa();
   bbb();
  }

  private void aaa()
  {
   string[] c=new string[3];
   //c=new string[3];
   c[0]="我們在";
   c[1]="西部E網";
   c[2]="學習C#";

  }

  private void bbb()
  {
   Response.Write(c[0]+c[1]+c[2]);
  }

  #region Web Form設計器產生的程式碼
  override protected void OnInit(EventArgs e)
  {
   InitializeComponent();
   base.OnInit(e);
  }
 
  private void InitializeComponent()
  {   
   this.Load += new System.EventHandler(this.Page_Load);
  }
  #endregion
 }
}

    運行後會我們發現,會有以下錯誤產生:

異常詳細資料: System.NullReferenceException: 未將對象引用設定到對象的執行個體。

源錯誤:

行 33:   private void bbb()
行 34:   {
行 35:    Response.Write(c[0]+c[1]+c[2]);
行 36:   }
行 37:
 
    很多初學者都會有疑問:我已經定義了變數 public string[] c,而且也進行了執行個體化 string[] c=new string[3],但是為什麼在調用數組c的時候還會報“未將對象引用設定到對象的執行個體”的錯誤呢?

    問題出在string[] c=new string[3]這裡,在前面已經將數組c定義後,在函數aaa()中再次將數組定義,造成前面定義的數組不能執行個體化。只需要將 string[] c=new string[3]修改成 c=new string[3] 即可。
 
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.