C#如何使用单个计时器通知其他类?

时间:2015-06-11 05:45:25

标签: c# timer delegates

我正在尝试创建一个全局计时器,其中一段时间​​后需要通知的所有内容都已过去。

例如,在游戏中,会有增益和攻击降温定时器和物品冷却等等。

单独管理它们很好,但是如何让它们全部在同一个计时器上运行?

我尝试使用SortedList,其中float作为键,而委托作为值,只是在时间到了时调用,但我似乎无法管理它。尝试使用Generic参数委托,但我无法将其放入排序列表中。

有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:1)

我可以指出两个选项:

  1. 创建一个类似TimerControlled的界面(所有名称都可以更改)使用方法TimerTick(whatever arguments you need)(以及其他需要的方法),它实现该类的计时器刻度逻辑。在每个使用定时器相关机制的类上实现接口。最后在你的基础(逻辑)类上将所有TimerControlled对象添加到一个数组(TimerControlled),这将允许你遍历该数组并用2行代码调用那些对象的TimerTick方法
  2. 接口:

    interface TimerControlled
    {
       void TimerTick();
    }
    

    在每个班级中实施它:

    public class YourClass: TimerControlled{
       ....
       public void TimerTick(){
          advanceCooldown();
          advanceBuffTimers();
       }
    }
    

    最后将您的课程添加到TimerControlled

    列表中
    class YourLogicClass{
       List<YourClass> characters= new List<YourClass>();
       private timer;
       List<TimerControlled> timerControlledObjects = new List<TimerControlled>();
       ...
       public void Initialize(){
          ... //your code, character creation and such
          foreach(YourClass character in characters){ //do the same with all objects that have TimerControlled interface implemented
             timerControlledObjects.add(character);
          }
          timer = new Timer();
          timer.Tick += new EventHandler(timerTick)
          timer.Start();
    
       } 
    
       public void timerTick(Object sender, EventArgs e){
          foreach(TimerControlled timerControlledObject in timerControlObjects){
             timerControlledObject.TimerTick();
          }
       }
    
    }
    
    1. (从长远来看,这不是一个非常好的选项)静态类中的静态计时器,如Global.timer,这意味着只存在该计时器的1个实例。然后将事件处理程序附加到每个相关类的计时器以处理计时器滴答。
    2. 代码:

      public static class Global{
      //I usually create such class for global settings
         public static Timer timer= new Timer();
      }
      
      
      
      class YourLogicClass{
         public void Initialize(){
             ... 
             Global.timer.Start();
         }
      }
      
      class YourClass{
      
         public YourClass(){
            Global.timer.tick += new EventHandler(timerTick);
         }
      
      
         private void timerTick(Object sender,EventArgs e){
            advanceCooldowns();
            advanceBuffTimers();
         }
      }
      

      请记住,我已经编写了代码,因此可能存在一些语法错误,但逻辑是正确的。

      如果您对答案有进一步的疑问,请离开。