【发布时间】:2013-02-01 13:45:18
【问题描述】:
我经常有一些重复的代码。
通常,我将它们放在一个函数中,但有时我讨厌这样做,因为:
- 需要的参数太多
- 代码通常只针对整体的一小部分。所以我终于有了两三个只用在一个地方的功能。
所以,为了模拟 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 代表使用这种方式。这就是为什么我想知道是否可以推荐这种做法,或者是否会导致我不知道的问题。
【问题讨论】:
-
我错过了这个问题,在这里可以找到关于这个用例的答案,以及很多 Action 委托使用:stackoverflow.com/questions/371054/…
标签: .net delegates action inline