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

发布于 2024-12-28 03:44:45 字数 754 浏览 2 评论 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

有什么方法可以避免这里出现代码重复吗?

I have the following code:

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

As you can see, I am trying to come up with a shared function that can be reused for every
month. The issue is that I need the following line in the All method:

otherForecasts.Sum(r => r.Feb)

to be generic but I need the callback inside the Sum method to be passed from outside (since I don't want it to be hardcoded as r.Feb.

Is there any way to avoid having code duplication here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不忘初心 2025-01-04 03:44:45

Expression> 传递到 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;
}

Pass an Expression<Func<Forecast, int>> into the All() method.

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文