![](/img/trans.png)
[英]Object reference not set to an instance of an object. c# RADTreeView telerik
[英]C# “Object reference not set to an instance of an object.”
當我嘗試使用與其連接的btn時收到該錯誤:
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是我在提高速度之前和之后使用並更新當前速度的面板。 plane
在以上定義為:
Airplane plane = new Airplane();
該錯誤似乎是在plane.Accelerate();
上發生的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()
根據VS告訴我的內容,第一行if(PlanePosition.speed < Position.MAX_SPEED)
一直在發生。
//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
那么PlanePosition
顯然為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
}
一般來說,當您嘗試使用尚未實例化的對象時,就會發生該錯誤。
因此,PlanePosition是類的名稱,您將需要實例化該類,然后將該方法與該對象一起使用。
PlanePosition myPlane = new PlanePosition();
myPlane.speed < ...
但是我認為沒有提供足夠的細節來提供比我給您的更具體的信息。 什么是PlanePosition? 類還是對象?
PlanePosition
尚未初始化。 您需要在調用Accelerate
之前確保將對象分配給PlanePosition
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.