2012-01-22 179 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我已經添加(未經測試)您的代碼修改 –