2011-01-20 147 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

相关问题