将对象列表写入文本文件

Ale*_*ddi 3 c# list streamwriter

我有一个这样的类菜:

public class Dish
{
    public Dish(int cost, string name)
    {
        Cost = cost;
        Name = name;
    }

    public int Cost { get; set; }
    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

在主窗体中,用户可以输入以前的数据。然后我创建一个“菜”列表:

public static List<Piatto> List = new List<Piatto>();
Run Code Online (Sandbox Code Playgroud)

我在一个静态类中创建了它,所以我可以从任何地方访问它。一旦一个项目被添加到列表中,我想将它保存在一个文本文件 (.txt) 中,所以我尝试使用这个:

public static void SaveToTxt()
    {
        using (TextWriter tw = new StreamWriter(Path))
        {
            foreach (var item in Data.List)
            {
                tw.WriteLine(item.ToString());
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

问题是,当我打开保存列表的文本文件时,我得到“WindowsFormsApplication1.Dish”。

如何保存到显示成本和名称的文本文件?

Ps 我想将列表保存在文本文件中,因为删除一行对我来说更容易,这是我不知道如何用二进制做的。

提前致谢。

编辑:

覆盖该ToString()方法工作正常。谢谢大家的回答!

pit*_*smx 5

youritem是一个包含多个属性的对象,您必须访问它们:

public static void SaveToTxt()
{
    using (TextWriter tw = new StreamWriter(Path))
    {
        foreach (var item in Data.List)
        {
            tw.WriteLine(string.Format("Item: {0} - Cost: {1}", item.Name, item.Cost.ToString()));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


suj*_*lil 5

很简单,你快到了,我想你忘了覆盖.ToString()你的类中的方法。通过覆盖该.ToString()方法,您可以返回其对象的字符串表示形式。您也可以格式化它们。所以你必须添加这个被覆盖的.ToString()方法才能让它工作。考虑以下代码

public class Dish
{
    public Dish(int cost, string name)
    {
        Cost = cost;
        Name = name;
    }

    public int Cost { get; set; }
    public string Name { get; set; }
    public override string ToString() 
    {
       return String.Format("Item Name :{0} \n Item Cost : {1}", this.Name,this.Cost);
    }
}
Run Code Online (Sandbox Code Playgroud)