在C#中存储方法列表
我有一个方法列表,我想按特定顺序调用。 因此,我希望将它们存储在有序列表或具有指定索引的表中。 这样,列表将是唯一可以改变我们想要更改呼叫顺序的日子。
我发现这篇文章解释了如何使用数组和委托来完成它。 但我在评论和其他一些地方读到它也可以使用Dictionary和LinQ来完成。 有什么建议吗?
您可以定义Action
对象,它们是返回void
参数委托。 每个动作都是指向方法的指针。
// Declare the list List actions = new List (); // Add two delegates to the list that point to 'SomeMethod' and 'SomeMethod2' actions.Add( ()=> SomeClass.SomeMethod(param1) ); actions.Add( ()=> OtherClass.SomeMethod2() ); // Later on, you can walk through these pointers foreach(var action in actions) // And execute the method action.Invoke();
Queue
怎么样?
var queue = new Queue(); queue.Enqueue(() => foo()); queue.Enqueue(() => bar()); while(queue.Count != 0) { Action action = queue.Dequeue(); action(); }
为什么不考虑使用Queue
it的FIFO,在Queue
存储委托,当你调用Dequeue
它会以指定的方式调用你的方法。
如何使用Multicast Delegate,它将委托存储在LinkList中,因此当您调用Invoke()时,它将以指定的方式调用。
我建议看看Command模式 。 希望这是你所期待的。
您可以使用List<>
来满足您的需求:
delegate void MyFunction(...); List delegateList;
如果您的委托返回void,则可以使用event
。 可以将多个代理添加到单个事件调用列表中,并按照添加的顺序进行调用。
delegate void MyEvent(...); event MyEventEventHandler MyEvent;
Dictionary
顺序是未定义的 ,它意味着进行查找。