我经常有一些重复的代码。
通常,我将它们放在一个函数中,但有时我讨厌这样做,因为:
- 它需要太多参数
- 代码通常只针对整体的一小部分。所以我终于有了两三个只用在一个地方的功能。
因此,为了模拟 C# 中缺少的内联代码,我使用 Action 委托:
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 代表以这种方式使用过任何地方。这就是为什么我想知道是否可以推荐这种做法,或者是否会导致我不知道的问题。