我该如何考虑这些代码以避免C#中的代码重复
本文关键字:代码 何考虑 | 更新日期: 2023-09-27 18:21:09
我有以下代码:
private int AllFeb(Forecast f, IRepository repository)
{
return All(f, repository, f.Feb);
}
private int AllJan(Forecast f, IRepository repository)
{
return All(f, repository, f.Jan);
}
private int All(Forecast f, IRepository repository, int callBk)
{
var otherForecasts = repository.Query<Forecast>().Where(r => r.PersonId == f.PersonId);
if (otherForecasts.Any())
{
return otherForecasts.Sum(r => r.Feb) + callBk;
}
return 0;
}
正如你所看到的,我正在尝试提出一个共享函数,它可以对每个月问题是我在All
方法中需要以下行:
otherForecasts.Sum(r => r.Feb)
是通用的,但我需要从外部传递Sum
方法内部的回调(因为我不希望它被硬编码为r.Feb
.
有什么方法可以避免这里的代码重复吗?
将Expression<Func<Forecast, int>>
传递到All()方法中。
private int AllFeb(Forecast f, IRepository repository)
{
return All(f, repository, f.Feb, r => r.Feb);
}
private int AllJan(Forecast f, IRepository repository)
{
return All(f, repository, f.Jan, r => r.Jan);
}
private int All(Forecast f, IRepository repository, int callBk, Expression<Func<Forecast, int>> projection)
{
var otherForecasts = repository.Query<Forecast>().Where(r => r.PersonId == f.PersonId);
if (otherForecasts.Any())
{
return otherForecasts.Sum(projection) + callBk;
}
return 0;
}