【问题标题】:How can i factor out this code to avoid code duplication in C#?我如何分解此代码以避免 C# 中的代码重复?
【发布时间】:2012-01-22 19:05:38
【问题描述】:

我有以下代码:

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

有什么办法可以避免代码重复?

【问题讨论】:

  • 您能说明您是如何声明 Forecast 的吗?

标签: c# refactoring code-duplication duplication


【解决方案1】:

Expression&lt;Func&lt;Forecast, int&gt;&gt; 传递给 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    相关资源
    最近更新 更多