【发布时间】:2023-03-14 02:47:01
【问题描述】:
我遇到了一个问题,我收到一条错误消息,指出我无法从“double”转换为“Car_Management.Car”。我在这里想念什么?这是我到目前为止所做的代码,我必须将汽车特性添加到列表中。另外,如何将列表输出到文本文件?
namespace Car_Management
{
class CarDM
{
public static void save(List<Car> fullList)
{
Car myCar = new Car();
List<Car> list = new List<Car>() {myCar.Model, myCar.Mileage, myCar.Colour, myCar.Year};
StreamWriter outputFile;
outputFile = File.CreateText("List.txt");
}
public static void load()
{
StreamReader inputFile;
inputFile = File.OpenText("List.txt");
}
}
}
这是我的另一门课
namespace Car_Management
{
class Car
{
private int year;
private double mileage;
private string colour;
private string model;
private string info;
//constructor
public Car()
{
year = 0;
mileage = 0;
colour = "";
model = "";
}
//name properties
public string Model
{
get { return model; }
set { model = value; }
}
public string Colour
{
get { return colour; }
set { colour = value; }
}
public double Mileage
{
get { return mileage; }
set { mileage = value; }
}
public int Year
{
get { return year; }
set { year = value; }
}
//returns string consisting of model, year, mileage, colour
public string GetInfo(string sep)
{
sep = ": ";
return model + sep + colour + sep + mileage.ToString("c") + sep + year.ToString();
}
}
}
【问题讨论】:
-
List<Car> list = new List<Car>() {myCar.Model, myCar.Mileage, myCar.Colour, myCar.Year};- 你到底打算做什么?您告诉它您正在尝试创建Car的列表,但提供的是Car的组件,而不是实际的Car对象。 -
您应该为您创建的对象赋值。例如 List
list = new List () {myCar.Model = "Malibu", myCar.Mileage = 150, myCar.Colour = color.Red, myCar.Year = 2015}; -
开始阅读 MSDN 文档并了解
.ToStrng()重载 msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx