【问题标题】:Printing components from a list of objects dont work从对象列表中打印组件不起作用
【发布时间】:2019-03-20 21:29:38
【问题描述】:
class DataBase
    {
        public string Name { get;  set; }
        public double Price { get;  set; }
        public double Quantity { get;  set; }
    }



 public static void GetProdInfo(List<DataBase> dataInfo)
            {
                foreach(var info in dataInfo)
                {
                    Console.WriteLine(info);
                }
            }

为什么我没有从数据库中获取数据,例如名称价格量化等,我正在获取类似的 MenuDatabaseUpdated.DataBase,请帮助我,我如何打印数据库的组件?

【问题讨论】:

标签: c#


【解决方案1】:

这取决于您要打印什么。

在这一行:

Console.WriteLine(info);

info 是类数据库的一个实例。当 Writeline 尝试打印“信息”或一般某个类的对象时,它会调用 ToString() 方法,默认情况下该方法是您的类的全名。因此,您必须重写 ToString 方法并创建类的字符串表示形式。

类似这样的:

class DataBase
{
    public string Name { get;  set; }
    public double Price { get;  set; }
    public double Quantity { get;  set; }

    public override string ToString()
    {
         return $"Name: {Name} Price: {Price} Quantity: {Quantity}";
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-12
    • 1970-01-01
    • 2022-01-09
    • 2017-03-09
    • 2020-02-21
    • 2019-04-26
    • 1970-01-01
    相关资源
    最近更新 更多