事件和行动方法

时间:2015-01-29 10:57:48

标签: c# events action

我有一些计时器。当时间结束时,我想调用一个事件。但我不知道如何在制作实例时为事件添加方法。 这是代码:

public delegate void DaysPassed(Action action);

    public class TimeAwait
    {
        public uint DaysLeft;
        public event DaysPassed Done;

        public TimeAwait(uint daysToWait, Action action)
        {
            DaysLeft = daysToWait;
            Done += action;
        }

2 个答案:

答案 0 :(得分:1)

你不需要在这里举办活动和代表。只需在正确的位置调用您的操作即可。例如:

    public class TimeAwait
    {
        public uint DaysLeft;
        private Action action;
        private System.Timers.Timer aTimer;

    public TimeAwait(uint daysToWait, Action a)
    {
        action = a;
        DaysLeft = daysToWait;

        aTimer = new System.Timers.Timer();
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        aTimer.Interval = daysToWait;
        aTimer.Enabled = true;

    }

    public void OnTimedEvent(object source, System.Timers.ElapsedEventArgs e)
    {
        action.Invoke();
        aTimer.Stop();
    }
}

    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Action someAction;
                someAction = () => Console.WriteLine(DateTime.Now);

            var item1 = new TimeAwait(2000, someAction);
            var item2 = new TimeAwait(4000, someAction);

            Console.ReadKey();
        }
        catch
        {

        }
    }
}

enter image description here

答案 1 :(得分:0)

如果您希望它能够调用传递的Action,那么这样的类应该可以解决问题。如果你想要能够注册除了创建者之外的其他监听器,你需要事件,在这种情况下我不会在构造函数中传递事件处理程序。

public class Countdown
{
     int _count;
     Action _onZero;

     public Countdown(int startValue, Action onZero)
     {
          _count = startValue;
          _onZero = onZero;
     }

     public void Tick()
     {
         if(_count == 0)
             return; //or throw exception

         _count--;
         if(_count == 0)
            _onZero();
     }
}