在C#中存储方法列表

Jla*_*Jla 18 .net c# .net-3.5

我有一个方法列表,我想按特定顺序调用.因此,我希望将它们存储在有序列表或具有指定索引的表中.这样,列表将是我们想要更改呼叫顺序的唯一一天.

我发现这篇文章解释了如何使用数组和委托来完成它.但我在评论和其他一些地方读到它也可以使用Dictionary和LinQ来完成.有什么建议吗?

Jan*_*oom 36

您可以定义Action对象,这些对象是返回的无参数委托void.每个动作都是指向方法的指针.

// Declare the list
List<Action> actions = new List<Action>();

// 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();
Run Code Online (Sandbox Code Playgroud)

  • 你可以省略Invoke()btw,只需调用action() (13认同)
  • 一切都很好,但队列更适合 OP 的任务,而不是列表,imo。不是吗? (2认同)
  • 不要这么认为.它只是一个静态列表,不需要排队或出队任务,因为它们不会动态变化.他可能想要重新运行批次几次等. (2认同)

aba*_*hev 7

怎么样Queue<Action>

var queue = new Queue<Action>();

queue.Enqueue(() => foo());
queue.Enqueue(() => bar());

while(queue.Count != 0)
{
    Action action = queue.Dequeue();
    action();
}
Run Code Online (Sandbox Code Playgroud)