0

私は次のコードを持っています:

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

ここでコードの重複を回避する方法はありますか?

4

1 に答える 1

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;
}
于 2012-01-22T19:10:58.700 に答える