问题
I often have some piece of code that repeats.
Usually, I put them in a function, but sometimes I hate to do this because :
- it requires too many parameters
- the code is usually very specific to a little part of the whole. So I finally have two or three function that are only used in one place.
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.
回答1:
As long as it doesn't get too confusing, there is nothing wrong with that.
回答2:
It is perfectly valid to have a function that is only called once if it makes the code easier to read and maintain.
来源:https://stackoverflow.com/questions/14647668/is-it-a-good-practice-to-use-action-delegates-as-inline-functions