【发布时间】:2012-06-11 23:26:58
【问题描述】:
我有一系列看起来非常相似但只有一行的函数,例如以下两个(但我还有更多):
private static int HowManyHoursInTheFirstYear(IList<T> samples)
{
DateTime firstDate = samples[0].Date;
int count = 0;
while (count < samples.Count &&
samples[count].Date.Year == firstDate.Year)
{
count++;
}
return count;
}
private static int HowManyDaysInTheFirstMonth(IList<T> samples)
{
DateTime firstDate = samples[0].Date;
int count = 0;
while (count < samples.Count &&
samples[count].Date.Month == firstDate.Month) // <--- only change!
count++;
}
return count;
}
我正在考虑使用委托以某种优雅的方式删除代码中的这种重复,这将允许我调用类似的东西:
HowManyDaysInTheFirstPeriod(
samples,
delegate(DateTime d1, DateTime d2) { return d1.Month == d2.Month; });
从而声明如下委托:
delegate bool DateComparer(DateTime first, DateTime second);
HowManyDaysInTheFirstPeriod 应该类似于以下内容:
private static int HowManySamplesInFirstPeriod
IList<T> samples,
DateComparer comparer)
{
DateTime firstDate = samples[0].Date;
int count = 0;
while (count < samples.Count && comparer())
{
count++;
}
}
不幸的是,编译器抱怨比较器需要两个参数。
我对 C# 比较陌生,在这里遇到了障碍。 你会如何解决这个问题?
【问题讨论】:
-
顺便说一句,对于那些说他们对 C# 很陌生的人来说,这是对委托的非常明智的使用。感谢您发现重复并将其分解到委托中。