是的,你可以通过使用List<Action>
或适合在我看来稍好一Queue<Action>
做到这一点。 Action
是一个无参数无效委托类型:
var functions = new Queue<Action>();
functions.Enqueue(() => Console.WriteLine("Foo"));
functions.Enqueue(() => Console.WriteLine("Bar"));
while (functions.Any())
{
// note the double parenthesis here: one for Dequeue
// and one for your dequeued function
functions.Dequeue()();
}
如果您需要的参数,使用Action<T>
为一体,Action<T, T>
两个等等。对于返回值,请使用Func
而不是Action
(或Func<T>
等)。
也许事件也会帮助你。事件是C#的语言功能,使用观察者模式。
// events are usually on the instance rather than static
private static event EventHandler MyEvent;
static void Main(string[] args)
{
MyEvent += (s, e) => Console.WriteLine("FooEvent");
MyEvent += (s, e) => Console.WriteLine("BarEvent");
MyEvent(null, EventArgs.Empty);
}
事件是多播委托,这是一个委托的功能一个列表。不过,您不能控制每个处理程序的线程:与上面的Queue<Action>
不同,您可以在其中启动或重新使用线程,多播委托从外部公开为一个请求,让您只对所有调用使用一个线程。
您可以使用C#的函数指针版本[代表](http://msdn.microsoft.com/en-us/library/ms173172.aspx)。 –
无论使用哪种方法,都要确保使用线程安全的'List'来确保线程之间不会出现同步问题。 –