提问者:小点点

在set method()中有问题。在设置价格[关闭]的值时显示错误


我想为每辆车设定价格,但它显示出一个错误

//vehicle program
using System;
namespace LAB_4
{
class Vehicle
{
    private string Brand;
    private string Model;
    private int Price;
    public string Getbrand()
     {return Brand;}
    public void Setbrand(string a)
    { Brand = a; }

    public string Getmodel()
    { return Model; }
    public void Setmodel(string a)
    { Model = a; }

    public int Getprice()
    { return Price; }
    public void Setprice(int a)
    { Price = a; }
    
}
class program
{
    static void Main(string[] args)
    {
        Vehicle Toyota = new Vehicle();
        Toyota.Setbrand("TOYOTA");
        Toyota.Setmodel("TOYOTA SIGMA 4");
        Toyota.Setprice = 9149000;
        Vehicle Suzuki = new Vehicle();
        Suzuki.Setbrand("HONDA");
        Suzuki.Setmodel("HONDA BR-V");
        Suzuki.Setprice = 34800000;
        Vehicle Faw = new Vehicle();
        Faw.Setbrand("AUDI");
        Faw.Setmodel("AUDI Q5");
        Faw.Setprice = 27000000;
        Console.WriteLine("================TOYOTA=============");
        Console.WriteLine("Toyota Sigma 4 Details are Given below");
        Console.WriteLine("Brand: {0}\nModel: {1}\nPrice: {2}", Toyota.Getbrand(),Toyota.Getmodel(), Toyota.Getprice());

        Console.WriteLine("================HONDA=============");
        Console.WriteLine("Honda BR-V Details are Given below");
        Console.WriteLine("Brand: {0}\nModel: {1}\nPrice: {2}", Suzuki.Getbrand(), Suzuki.Getmodel(),Suzuki.Getprice());

        Console.WriteLine("================AUDI=============");
        Console.WriteLine("AUDI Q5 Details are Given below");
        Console.WriteLine("Brand: {0}\nModel: {1}\nPrice: {2}", Faw.Getbrand(), Faw.Getmodel(), Faw.Getprice());
        Console.ReadKey();
    }
}

}


共1个答案

匿名用户

您可以使用C#中包含的属性,有一个属性叫做自动实现的属性,它使您的程序比使用方法更简洁

基本上在您的程序上,您可以这样做(我没有使用自动实现的属性)

private string brand = "";
private string model = "";
private int price;

public string Brand{ get{ return brand; } set{ brand = value; } }
public string Model{ get{ return model; } set{ model = value; } }
public int Price{ get{ return price; } set{ price = value; } }

并且基本上可以使用对象初始化来初始化类上的所有属性

Vehicle Toyota = new Vehicle{ Brand = "Toyota", Model = "Toyota Sigma", Price = 1000};

然后打印所有需要打印的数据。