如何分解这些代码以避免C#中的代码重复?

时间:2012-01-22 19:05:39

标签: c# refactoring code-duplication duplication

我有以下代码:

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

有没有办法避免代码重复?

1 个答案:

答案 0 :(得分:3)

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;
}