Sam*_*ham 78
我会使用一个看起来像这样的循环
for(DateTime date = begin; date <= end; date = date.AddDays(1))
{
}
Run Code Online (Sandbox Code Playgroud)
相应地设置开始和结束
Osc*_*Ryz 20
实现Iterator设计模式的另一个选择:
这可能听起来没必要,但我依赖于您如何使用此功能,您也可以实现Iterator设计模式.
想一想.假设一切正常,你复制/粘贴"for"句子.突然作为要求的一部分,你必须迭代所有的日子,但跳过其中一些(如日历,跳过瞻礼,周末,习俗等)
您必须创建一个新的"剪切"并改为使用日历.然后搜索并替换所有你的.
在OOP中,这可以使用Iterator模式来实现.
来自Wikpedia:
在面向对象的编程中,Iterator模式是一种设计模式,其中迭代器用于顺序访问聚合对象的元素,而不暴露其底层表示.Iterator对象封装了迭代发生方式的内部结构.
所以我的想法是使用这样的结构:
DateTime fromDate = DateTime.Parse("1/1/2009");
DateTime toDate = DateTime.Parse("12/31/2009");
// Create an instance of the collection class
DateTimeEnumerator dateTimeRange =
new DateTimeEnumerator( fromDate, toDate );
// Iterate with foreach
foreach (DateTime day in dateTimeRange )
{
System.Console.Write(day + " ");
}
Run Code Online (Sandbox Code Playgroud)
然后,如果需要,您可以创建子类来实现不同的算法,一个使用AddDay(1),另一个使用AddDay(7)或其他简单使用Calendar.等等
想法是降低对象之间的耦合.
同样,对于大多数情况来说,这将是过度的,但如果迭代形成系统的相关部分(假设您正在为企业创建某种类型的通知,并且应该遵循不同的全球化)
当然,基本实现将使用for.
public class DateTimeEnumerator : System.Collections.IEnumerable
{
private DateTime begin;
private DateTime end;
public DateTimeEnumerator ( DateTime begin , DateTime end )
{
// probably create a defensive copy here...
this.begin = begin;
this.end = end;
}
public System.Collections.IEnumerator GetEnumerator()
{
for(DateTime date = begin; date < end; date = date.AddDays(1))
{
yield return date;
}
}
}
Run Code Online (Sandbox Code Playgroud)
只是一个想法:)
DateTime dateTime = new DateTime(2009, 1, 1);
while(dateTime.Year < 2010)
{
dateTime = dateTime.AddDays(1);
}
Run Code Online (Sandbox Code Playgroud)
我使用MiscUtil及其扩展方法:
foreach(DateTime date in 1.January(2009)
.To(31.December(2009))
.Step(1.Days())
{
Console.WriteLine(date);
}
Run Code Online (Sandbox Code Playgroud)