{
_cars = new List<Car>{
new Car { Id = 1, BrandId = 1, ColorId = 13, DailyPrice = 30000, Description = "BMW 5.20", ModelYear = 2023, BrandName = "BMW"},
new Car { Id = 2, BrandId = 1, ColorId = 13, DailyPrice = 5, Description = "BMW 5.20", ModelYear = 2023, BrandName= "B"},
new Car { Id = 3, BrandId = 3, ColorId = 10, DailyPrice = 25000, Description = "Mercedes C180", ModelYear = 2023, BrandName="Mercedes"},
new Car { Id = 4, BrandId = 5, ColorId = 11, DailyPrice = 21000, Description = "Hyundai i20n", ModelYear = 2023, BrandName= "BMW"},
new Car { Id = 5, BrandId = 3, ColorId = 10, DailyPrice = 40000, Description = "Mercedes A180", ModelYear = 2023, BrandName="Mercedes"},
};
}
public void Add(Car car)
{
if (car.DailyPrice > 10 && car.BrandName.Length > 2)
{
_cars.Add(car);
}
else {
Console.WriteLine("Error");
}
我应该获取第二辆新车(id2)的错误消息。但我不接受,它确实有效,我可以在我的控制台上看到它。我在这里做错了什么?也许这是很简单的事情,但我是软件初学者。
如果汽车价格低于 10 并且汽车品牌名称低于 2 个字符,我会尝试获取错误消息。
您的代码看起来不完整,您提出的问题也不是很容易理解。
据我所知,这应该有帮助:
using System;
using System.Collections.Generic;
public class Car
{
public int Id { get; set; }
public int BrandId { get; set; }
public int ColorId { get; set; }
public decimal DailyPrice { get; set; }
public string Description { get; set; }
public int ModelYear { get; set; }
public string BrandName { get; set; }
}
public class CarManager
{
private List<Car> _cars = new List<Car>
{
new Car { Id = 1, BrandId = 1, ColorId = 13, DailyPrice = 30000, Description = "BMW 5.20", ModelYear = 2023, BrandName = "BMW"},
new Car { Id = 2, BrandId = 1, ColorId = 13, DailyPrice = 5, Description = "BMW 5.20", ModelYear = 2023, BrandName= "B"},
new Car { Id = 3, BrandId = 3, ColorId = 10, DailyPrice = 25000, Description = "Mercedes C180", ModelYear = 2023, BrandName="Mercedes"},
new Car { Id = 4, BrandId = 5, ColorId = 11, DailyPrice = 21000, Description = "Hyundai i20n", ModelYear = 2023, BrandName= "BMW"},
new Car { Id = 5, BrandId = 3, ColorId = 10, DailyPrice = 40000, Description = "Mercedes A180", ModelYear = 2023, BrandName="Mercedes"},
};
public void Add(Car car)
{
if (car.DailyPrice > 10 && car.BrandName.Length > 2)
{
_cars.Add(car);
}
else
{
Console.WriteLine("Error: The car must have a daily price greater than 10 and a brand name longer than 2 characters.");
}
}
}
class Program
{
static void Main()
{
CarManager carManager = new CarManager();
Car newCar1 = new Car
{
Id = 6,
BrandId = 2,
ColorId = 14,
DailyPrice = 15000,
Description = "Audi A4",
ModelYear = 2023,
BrandName = "Audi"
};
Car newCar2 = new Car
{
Id = 7,
BrandId = 4,
ColorId = 12,
DailyPrice = 8,
Description = "Cheap Car",
ModelYear = 2023,
BrandName = "CC"
};
carManager.Add(newCar1); // This should be added successfully.
carManager.Add(newCar2); // This should print an error message.
}
}
说明:
给定的解决方案确保只有符合指定标准的汽车才会添加到列表中,从而保持汽车集合的完整性。