【问题标题】:Is it a good practice to use Action delegates as Inline functions?将 Action 委托用作内联函数是一种好习惯吗?
【发布时间】: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 代表使用这种方式。这就是为什么我想知道是否可以推荐这种做法,或者是否会导致我不知道的问题。

【问题讨论】:

标签: .net delegates action inline


【解决方案1】:

只要不是太混乱,就没有错。

【讨论】:

    【解决方案2】:

    如果使代码更易于阅读和维护,那么只调用一次的函数是完全有效的。

    【讨论】:

      猜你喜欢
      • 2011-03-02
      • 1970-01-01
      • 1970-01-01
      • 2015-02-18
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-11
      相关资源
      最近更新 更多