[英]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;
}
您不需要事件和代表。 只需在正确的位置调用您的操作即可。 例如:
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
{
}
}
}
如果您只希望这样的类能够调用传递的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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.