Factoring out skeleton processing (C#)
Is there a language construct in C# that allows the abstraction of loop (or other) "outer" processing?
I have a fairly straight forward nested structure (lists of lists of ints say) and the code to "spin" through each of the lowest level ints. The code isn't complicated (nor particularly long) but I have multiple functions thats need to "interact" with the lowest level independently and have been just copying the loop skeleton to do so. Seems like a waste to me.
foreach (list in outerlists)
... a few random lines of structure traversing
foreach (int in list)
do something simple to int
This is obviously a scaled down example but my real world is similar - I end up copying the outer processing repeatedly to change out relatively few inner lines of work.
My t开发者_StackOverflow中文版entative solution is to make a "processing" method that contains the loops and takes an enumeration (or something) parameter to tell it which inner function to call. Then put a switch statement at the "do something" level which calls the correct sub function.
Am I on the right track or is there an easier way? I could get rid of the switch statement with a concept of function pointers (just pass a function pointer into the processing loop and call it at the do something level) but don't know if that is possible in C#?
(elaborating a bit on Oded's answer)
Assuming you always want to iterate the same way and that the only thing different between the copy-pasted foreach's is the innermost nested block then you could encapsulate all the looping into a method:
public void DoStuffOnInnerElements (Action<int> theStuffToDo)
{
foreach (var subList in outerLists)
{
// a few random lines here...
foreach (int item in subList)
{
theStuffToDo(item);
}
}
}
The action can be any of the formats that C# accepts for delegates (a delegate is C#'s answer to C/C++ function pointers):
// Lambdas
DoStuffOnInnerElements((i) => Console.WriteLine(i));
// Methods
DoStuffOnInnerElements(My_Void_xxx_Int_Method);
DoStuffOnInnerElements(new Action<int>(Console.WriteLine));
// anonymous delegates
DoStuffOnInnerElements(delegate(int i) { Console.WriteLine(i); });
// etc.
You can pass in an Action
delegate - this will be the function doing the actual operation within the outer loop.
精彩评论