代码之家  ›  专栏  ›  技术社区  ›  Jla

用C语言存储方法列表#

  •  17
  • Jla  · 技术社区  · 15 年前

    我有一个我想按特定顺序调用的方法列表。因此,我想将它们存储在一个有序的列表中,或者存储在一个具有指定索引的表中。这样的话,名单将是唯一的事情,以改变当天我们要改变的通话顺序。

    this article 解释如何使用数组和委托执行此操作。但我在评论和其他地方看到,也可以使用字典和/或LinQ。有什么建议吗?

    5 回复  |  直到 15 年前
        1
  •  38
  •   Jan Jongboom    15 年前

    你可以定义 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();
    
        2
  •  8
  •   abatishchev Karl Johan    15 年前

    来一杯怎么样 Queue<Action> ?

    var queue = new Queue<Action>();
    
    queue.Enqueue(() => foo());
    queue.Enqueue(() => bar());
    
    while(queue.Count != 0)
    {
        Action action = queue.Dequeue();
        action();
    }
    
        3
  •  4
  •   TalentTuner    15 年前

    你为什么不考虑使用 Queue 排队 当你打电话的时候 Dequeue

    使用多播委托怎么样,它将委托存储在链接列表中,因此当您调用Invoke()时,它将以指定的方式被调用。

        4
  •  0
  •   Arseny    15 年前

    我建议你看看 Command pattern

        5
  •  0
  •   Wernight    15 年前

    你可以用 List<>

    delegate void MyFunction(...);
    List<MyFunction> delegateList;
    

    如果您的委托返回void,您可以使用 event

    delegate void MyEvent(...);
    event MyEventEventHandler MyEvent;
    

    Dictionary order is undefined