2011-01-20 49 views
0

我得到的錯誤,當我嘗試使用連接到它的BTN:C#「對象引用未設置爲對象的實例。」

private void btnAccel_Click(object sender, EventArgs e) 
      { 

       pStatus.Text = plane.speed.ToString(); 
       plane.speed = double.Parse(txtSpeed.Text); 
       plane.Accelerate(); 
       pStatus.Text = plane.speed.ToString(); 
      } 

pStatus是我使用的面板,並更新當前的速度之前和之後我提高速度。

Airplane plane = new Airplane(); 

的錯誤似乎當它到達plane.Accelerate();

public void Accelerate() 
     { 
      // increase the speed of the airplane 

      if (PlanePosition.speed < Position.MAX_SPEED) 
      { 
       PlanePosition.speed = PlanePosition.speed + 1; // or speed += 1; 
      }//end of if 
      numberCreated++; // increment the numberCreated each time an Airplane object is created 

     }//end of public Accelerate() 

也就是說第一行if(PlanePosition.speed < Position.MAX_SPEED)是它不斷從什麼VS告訴我發生的事情發生: plane如上定義。


//private variables 
     private string name{get; set;} 
     private Position planePosition; 
     private static int numberCreated; 

     //default constructor 
     public Airplane() 
     { 

     }//end of public Airplane 


     public Position PlanePosition{get;set;} 

class Position 
    { 
     //private variables 
    internal int x_coordinate; 
    internal int y_coordinate; 
    internal double speed; 
    internal int direction; 
    internal const int MAX_SPEED = 50; 

     //default constructor 
     public Position() 
     { 

     }//end of public Position 

     public string displayPosition() 
     { 
      return "okay"; 
     }//end of public string displayPosition() 
    }//end of class Position 
+0

之前,您需要確保將對象分配給PlanePosition,好像您沒有初始化PlanePosition字段/屬性。 – siride 2011-01-20 16:01:52

+0

您應該發佈PlanePosition和Position的代碼 – hackerhasid 2011-01-20 16:01:55

+0

是PlanePosition還是定位對類的引用?如果是這樣,確保你已經實例化它,就像你的飛機類一樣。 – Bernard 2011-01-20 16:03:12

回答

1

然後​​顯然null。你可能缺少

PlanePosition = new Position(); // or whatever the type of PlanePosition is 
在構造函數

Airplane

private PlanePosition = new Position(); 

初始化字段或類似,如果它是一個屬性。

我看到你離開這樣的評論到另一個答案:

public Position PlanePosition{get;set;}

所以這是一個自動的財產,你不進行初始化。因此,它會收到參考類型爲null的默認值。你需要在構造函數初始化此:

public Airplane() { 
    this.PlanePosition = new Position(// parameters for constructor); 
    // rest of constructor 
} 
0

一般來說,當您嘗試使用,你有沒有實例化一個對象會發生錯誤。

所以PlanePosition是類的名稱,您將要實例化該類,然後將該方法與對象一起使用。

PlanePosition myPlane = new PlanePosition(); 
myPlane.speed < ... 

但我不認爲有足夠的細節提供比我給你更具體。什麼是平面位置?一個類或一個對象?

0

​​未被初始化。在調用Accelerate

相關問題