创建汽车课程教程

时间:2018-10-27 19:02:59

标签: c# class

我目前正在尝试创建执行以下任务的汽车类:提供年份,制造商和速度。我能够完成大多数代码,但是在尝试创建我的汽车对象时当前遇到以下错误。另外,我尝试尽可能多地添加注释,以了解我的代码到底在做什么。如果错误,请更正我的评论,以便我更好地了解这些代码行的确切作用。下面是我的代码:

public partial class Form1 : Form
{
    // Declaring the class
    private Car myCar;

    public Form1()
    {
        InitializeComponent();
    }

    // GetCarData method that accepts Car object as an argument
    private void GetCarData()
    {
        // Creating the car object
        Car myCar = new Car();

        try
        {
            // Get the car year and model
            myCar.year = int.Parse(yearTextBox.Text);

            myCar.make = makeTextBox.Text;

            myCar.speed = 0;

        }
        catch (Exception ex)
        {
            // Display error message
            MessageBox.Show(ex.Message);
        }
    }

    // Display speed data when either acceleration or break button is clicked
    private void accelerateButton_Click(object sender, EventArgs e)
    {
        GetCarData();
        myCar.accelerate(5);
        MessageBox.Show("Your car is traveling at " + myCar.speed + " mph.");
    }

    private void breakButton_Click(object sender, EventArgs e)
    {
        GetCarData();
        myCar.brake(5);
        MessageBox.Show("Your car is traveling at " + myCar.speed + " mph.");
    }
}

我收到“没有给出与'Car.Car(int,string,int)'的所需形式参数'year'相对应的参数”错误

这是我的课程:

class Car
{
    // Fields 
    private int _year; // Year of the car
    private string _make; // Make of the car
    private int _speed; // Speed of the car

    //Constructor
    public Car(int year, string make, int speed)
    {
        _year = 2010;
        _make = "Mitsubishi";
        _speed = 0;
    }

    // Year property
    public int year
    {
        get { return _year; }
        set { _year = value; }
    }

    // Make property
    public string make
    {
        get { return _make; }
        set { _make = value; }
    }

    // Speed property
    public int speed
    {
        get { return _speed; }
        set { _speed = value; }
    }

    public void accelerate(int increaseSpeed)
    {
        // When speed button is pushed, it increases the speed
        speed = speed + increaseSpeed;
    }

    public void brake(int decreaseSpeed)
    {
        // When break button is pushed, it decreases the speed
        speed = speed - decreaseSpeed;
    }


}

1 个答案:

答案 0 :(得分:-1)

GetCarData()方法中,不要使用空的Car对象然后设置其属性,而应使用构造函数:

Car myCar = new Car(int.Parse(yearTextBox.Text), int.Parse(yearTextBox.Text), 0);

您会收到此错误,因为编译器正在Car类中寻找默认构造函数,而该构造函数不存在。 有关更多信息,请参见Should we always include a default constructor in the class?