事件和动作方法
events and action methods
我有一个计时器。当时间用完时,我想调用一个事件。但是我不知道如何在创建实例时向事件添加方法。 这是代码:
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;
}
A class 如果您只是希望它能够调用传递的 Action,那么这样的 class 应该可以解决问题。如果您希望能够注册除创建者之外的其他侦听器,您需要事件,在这种情况下我不会在构造函数中传递事件处理程序。
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();
}
}
这里不需要事件和代表。只需在正确的位置调用您的操作即可。例如:
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
{
}
}
}