列表显示对象状态

时间:2013-04-25 17:08:32

标签: c# list iteration

当我打印我的列表(库存)时,它会多次打印相同的值,而不是正确迭代:

List<Coffee> inventory = new List<Coffee>();

        Console.Write("Enter q to quit or the whole data as a comma delimited string using the following format Name,D,C,D:minQ or R:roast ");
        string s = Console.ReadLine();
        string[] values = s.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

        // Loop
        while (!s.ToLower().Equals("q"))
        {
            string name = values[0];
            string demand = (values[1]);
            string cost = (values[2]);
            string min = values[3];


            float D = CheckDemand(demand);
            float C = CheckCost(cost);
            float M = CheckMin(min);

            Decaf decafCoffee = new Decaf(name, D, C, M);
                   inventory.Add(decafCoffee);

            Console.Write("\nEnter q to quit or the whole data as a comma delimited string using the following format Name,D,C,D:minQ or R:roast: ");
            s = Console.ReadLine();
        }   // End loop

        // Display values
        Console.WriteLine("\nName \t   C ($)      Demand \t  Detail   Q(lbs.)     TAC ($)      T(weeks) ");
        for (int j = 0; j < inventory.Count; j++)
        {
            Console.WriteLine("{0}", inventory[j].toString());
        }

为什么会这样?我需要实现某个界面吗?

3 个答案:

答案 0 :(得分:2)

在while循环中使用string[]值移动您的行:

 string s = Console.ReadLine();
 // Loop
 while (!s.ToLower().Equals("q"))
 {
      string[] values = s.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
      ...

答案 1 :(得分:1)

当您在对象上调用ToString()时,通常只会获得该类型的完全限定名称。这取决于你想看到的打印,但你应该尝试显示Coffee类的成员。例如:

foreach(Coffee c in inventory)
{
   Console.WriteLine(c.Name);
}

我继续将您从for循环切换到foreach

答案 2 :(得分:0)

你需要把

string[] values = s.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

在你的while循环中。