2012-01-22 140 views
0

我有以下代码:如何将此代码分解以避免C#代码重复?

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

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

+0

你能告诉你如何声明预测吗? – Maggie

回答

3

传递一个Expression<Func<Forecast, int>>进入全()方法。

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

你能澄清吗? – leora

+0

@leora我已经添加(未经测试)您的代码修改 –