我正在寻找一种在我的代码中实现 DRY 原则的方法。我有一个这样的代码。
private static bool Inconsistent(AdStats adStat)
{
return
adStat.Daily.Impressions != adStat.Hourly.Sum(h => h.Value.Impressions) ||
adStat.Daily.Clicks != adStat.Hourly.Sum(h => h.Value.Clicks) ||
adStat.Daily.Spent != adStat.Hourly.Sum(h => h.Value.Spent) ||
adStat.Daily.SocialImpressions != adStat.Hourly.Sum(h => h.Value.SocialImpressions) ||
adStat.Daily.SocialClicks != adStat.Hourly.Sum(h => h.Value.SocialClicks) ||
adStat.Daily.SocialSpent != adStat.Hourly.Sum(h => h.Value.SocialSpent) ||
adStat.Daily.UniqueImpressions != adStat.Hourly.Sum(h => h.Value.UniqueImpressions) ||
adStat.Daily.UniqueClicks != adStat.Hourly.Sum(h => h.Value.UniqueClicks) ||
adStat.Daily.SocialUniqueImpressions != adStat.Hourly.Sum(h => h.Value.SocialUniqueImpressions) ||
adStat.Daily.SocialUniqueClicks != adStat.Hourly.Sum(h => h.Value.SocialUniqueClicks);
}
然后在社区的帮助下,我得到了一个很好的解决方案。
Func<AdStatsItem, int>[] metricGetters = {
s => s.Impressions,
s => s.Clicks,
s => s.Spent,
//...
};
return metricGetters.Any(getter => getter(adStat.Daily)
!= adStat.Hourly.Sum(h => getter(h.Value)));
但是我想不出一种方法来对具有多个分配的代码使用相同的技术。
hourly.Impressions += delta.Impressions;
hourly.Clicks += delta.Clicks;
hourly.Spent += delta.Spent;
hourly.SocialImpressions += delta.SocialImpressions;
hourly.SocialClicks += delta.SocialClicks;
hourly.SocialSpent += delta.SocialSpent;
hourly.UniqueImpressions += delta.UniqueImpressions;
hourly.SocialUniqueImpressions += delta.SocialUniqueImpressions;
hourly.UniqueClicks += delta.UniqueClicks;
hourly.SocialUniqueClicks += delta.SocialUniqueClicks;
经过一番思考,我想出了这个。
Expression<Func<AdStatsItem, int>>[] metricGetters = {
stat => stat.Impressions,
stat => stat.Clicks,
//...
};
var type = typeof (AdStatsItem);
foreach (var metric in metricGetters)
{
var body = (MemberExpression)metric.Body;
var propertyName = body.Member.Name;
var prop = type.GetProperty(propertyName);
var val = (int)prop.GetValue(hourly, null) + (int)prop.GetValue(delta, null);
prop.SetValue(hourly, val, null);
}
但是反射的使用真的让我很烦恼。有没有更好的方法摆脱上述冗余?