【发布时间】:2019-04-18 09:37:57
【问题描述】:
对于下面的代码,当我从“for”循环中显示日期时,我得到了预期的答案,但是当我将日期存储在列表中时,我得到了一些其他输出。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class dateshow
{
static void Main(string[] args)
{
List<DateTime> allDates = new List<DateTime>();
DateTime startDate = Convert.ToDateTime("2018-03-03");
DateTime endDate = Convert.ToDateTime("2018-03-15");
for (DateTime date = startDate; date <= endDate; date = date.AddDays(1))
{
allDates.Add(date);
Console.WriteLine(date);
Console.WriteLine(allDates); //ERROR : doesnt display the dates, instead displays System.Collections.Generic.List`1[System.DateTime]
}
}
}
}
我哪里出错了?
【问题讨论】:
-
使用
for-loop遍历生成的列表并输出其值。 -
或使用
string.Join,例如Console.WriteLine(string.Join(',', allDates))。虽然如果你想在循环中内部这样做,我会感到惊讶。 -
使用以下代码:Console.WriteLine(string.Join(",", allDates.Select(x => x.ToString())));