我遇到了一個問題,我收到一個錯誤,說我無法從'double'轉換爲'Car_Management.Car'。我在這裏錯過了什麼?這是我迄今爲止所做的代碼,我必須將汽車特性添加到列表中。另外,我怎樣才能將列表輸出到文本文件?爲什麼不能從Car_Management.Car轉換爲double或int或字符串
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 list = new List (){myCar.Model,myCar.Mileage,myCar.Colour,myCar.Year};' - 你打算做什麼?你告訴它你試圖創建一個'Car'的列表,但是提供一個'Car'的組件,而不是一個實際的Car'對象。 –
您應該將值分配給您創建的對象。例如列表 list = new List (){myCar.Model =「Malibu」,myCar.Mileage = 150,myCar.Colour = color.Red,myCar.Year = 2015}; –
Auguste
開始閱讀MSDN文檔,並瞭解'.ToStrng()'重載https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx – MethodMan