另一种选择:
List> actions = new List > { doStuff1, doStuff2, doStuff3, doStuff4, doStuff5 }; foreach (Action action in actions) { foreach (Foo x in list) { action(x); } }
刚检查,这是有效的.例如:
using System; using System.Collections.Generic; public class Test { static void Main(string[] args) { var actions = new List> { First, Second }; foreach (var action in actions) { foreach (string arg in args) { action(arg); } } } static void First(string x) { Console.WriteLine("First: " + x); } static void Second(string x) { Console.WriteLine("Second: " + x); } }
跑步的结果 Test.exe a b c
First: a First: b First: c Second: a Second: b Second: c
如果你有一个相当常量的动作列表,你可以避免使用foreach循环,但仍然显式地执行动作(尚未测试代码):
list.ForEach(action1); list.ForEach(action2); list.ForEach(action3); list.ForEach(action4);
Jon Skeet的答案很棒(我刚刚投了票).这是一个进一步发展的想法:
如果你做了很多,你可以制作一个名为"DoActionsInOrder"的扩展方法(或者你可以想出一个更好的名字).这是个主意:
public static void DoActionsInOrder(this IEnumerable stream, params Action actionList) { foreach(var action in actionList) { foreach(var item in stream) { action(item); } } }
然后,你可以像这样调用它:
myList.DoActionsInOrder(doStuff1, doStuff2, doStuff3, doStuff4, doStuff5);