对于下面的代码,当我从“ 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]
}
}
}
}
我要去哪里错了?
答案 0 :(得分:1)
allDates
是DateTime
对象的列表,这就是为什么您得到以下内容的原因:
System.Collections.Generic.List`1[System.DateTime]
您需要分别遍历allDates
变量。
foreach (var date in allDates)
{
Console.WriteLine(date.ToString());
}
答案 1 :(得分:1)
这种方式:
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);
allDates.ForEach(x => Console.WriteLine(x));
}
}
或者:
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(string.Join(",", allDates));
}
}