当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Class and Methods

问题描述:

I'm not sure what exactly to ask. I have created a class named Car when I click the Accelerate button on Form1 I want it to accelerate 5 increments. I need to use the method Accelerate from the Car class to do this. I thought I was calling it correctly but nothing is working. I need simple answers as I am a beginner.

namespace Car_Class

{

class Car

{

public string _year;

public string _make;

public double _speed;

public Car(string year, string make, double speed)

{

_year = year;

_make = make;

_speed = 0;

}

public string Year

{

get { return _year; }

set { }

}

public string Make

{

get { return _make; }

set { }

}

public double Speed

{

get { return _speed; }

set { }

}

public double Accelerate()

{

return _speed += 5;

}

public double Brake()

{

return _speed -= 5;

}

}

}

THEN the button....

namespace Car_Class

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

private void accButton_Click(object sender, EventArgs e)

{

string _year = "";

string _make = "";

int _speed = 0;

Car acc = new Car(_year, _make, _speed);

acc.Accelerate();

currentspeedListBox.Text = ???????

}

}

}

网友答案:

You need to set currentspeedListBox.Text = acc.Speed.ToString()

Are you aware that you won't see an increasing speed but you'll only see 5? You are creating a new car when you hit the box (starts at 0) then you increment it by 5 when you accelerate. After everything is done, the car goes away and if you hit the button again the process starts over. (Creates a new car at speed 0, then increments it to 5)

If you want to keep seeing an increase in the textbox you need to put the car as a private variable in Form1, or you need to take the speed that you produced (5) and store it as a private variable outside of the method.

Edit:

private Car _car = new Car("","",0)

private void accButton_Click(object sender, EventArgs e)
{
     _car.Accelerate();
     currentspeedListBox.Items.Add(car.Speed.ToString());
}

I assumed textbox even though it said otherwise. A ListBox is a container of many items, so it has an Items Property that has everything in it. The Text Property for a listBox refers to which one is currently selected in the listbox. Since there is nothing in the list box then nothing is selected (or appears). You need to add items to the ListBox, and in this case, the current acceleration.

网友答案:

your problem is that you are creating a new car each time you click the button

You need a car that is a member of the form

Form1 is a class just like Car is . Add A member _car of type car to it (Just after the class statement)

In the constructor of the form go

_car = new Car();

In the click method do

_car.Accelerate();
分享给朋友:
您可能感兴趣的文章:
随机阅读: