我經常有一些代碼重複。使用Action委託作爲內聯函數是否是一種很好的做法?
通常情況下,我把它們放在一個功能,但有時我不想這樣做,因爲:
- 它需要太多的參數
- 的代碼通常是非常具體的,以整體的一小部分。所以我終於有兩個或三個功能,只在一個地方使用。
因此,模擬是從C#缺少內嵌代碼,我用行動代表:
public void Display(DateTime from, DateTime to)
{
var start = from.ToOADate();
var end = to.ToOADate();
[...]
// This Action delegate helps me not to repeat the code.
var removePoints = new Action<Series>(serie =>
{
var pointsToRemove = serie.Points.Where(pt => pt.XValue < start || pt.XValue > end).ToArray();
foreach (var pt in pointsToRemove)
serie.Points.Remove(pt);
});
removePoints(FlameTemperatureSerie);
removePoints(BoshGasFlowRateSerie);
removePoints(PercCOSerie);
removePoints(PercH2Serie);
[...]
}
這是非常有幫助的,特別是因爲Action委託執行上下文可以使用局部變量。
我似乎對我很好,但我從來沒有見過無處活動的代表使用這種方式。這就是爲什麼我想知道這種做法是否可以被推薦,或者如果可能導致我不知道的問題。
我錯過了這個問題,可以找到有關此用例的答案,再加上很多Action委託使用:http://stackoverflow.com/questions/371054/uses-of-action-delegate-in-c-尖銳?RQ = 1 – Larry