它是用行动代表作为内联函数的好的做法呢?内联、它是、函数、做法

2023-09-06 16:23:12 作者:仙女味的小可爱

我经常有一些片code,重复。

I often have some piece of code that repeats.

通常情况下,我把它们放在一个功能,但有时我不想这样做,因为:

Usually, I put them in a function, but sometimes I hate to do this because :

在它需要太多的参数 的code通常是非常具体的,整个的一小部分。所以,我终于有两个或三个功能只在一个地方使用。

所以,模拟内嵌code这是从C#的缺失,我用行动代表:

So, to simulate Inline code which is missing from C#, I use Action delegates :

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);

    [...]
}

这是非常有帮助的,特别是因为这个动作代表执行上下文可以使用局部变量。

This is quite helpful, especially because the Action delegate execution context can use the local variables.

我似乎对我好,但我从来没有见过无处行动代表采用此种方式。这就是为什么我想知道,如果这种做法可建议,或者强权导致的问题我不知道。

I seems good to me, but I never saw nowhere Action delegates used this way. That's why I would like to know if this practice could be recommended, or if might causes issues I dont know.

推荐答案

只要它不会过于混乱,没有什么错。

As long as it doesn't get too confusing, there is nothing wrong with that.