注册计时器经过的事件 [英] Registering for timer elapsed events

查看:86
本文介绍了注册计时器经过的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个初始化计时器的类,该计时器将用作其他类成员为计时器经过的事件注册自己的中央核心。我的问题是我真的不知道如何向其他类公开计时器经过的事件。我认为可能可行的一种解决方案是,将计时器公开为一个公共属性,它将返回计时器对象,并且可以从该对象调用计时器经过的事件,例如:

I want to create a class that initializes a timer which will be used as a central core for other class members to register themselves for the timer elapsed event. My problem is that I don't really know how to expose the timer elapsed event to other classes. One solution, that I think might work is that I simply expose the timer as a public property which will return the timer object and I can call the timer elapsed event from this object, for example:

MyAppTimer appTimer = new MyAppTimer();
Timer timer = appTimer.GetAppTimer;
timer.Elapsed += SomeMethod;

但是使用此解决方案,我将暴露整个我不需要的计时器。如何在MyAppTimer类中传入一个方法,该方法将在内部将计时器的已过事件注册到该方法?与代表有关吗?也许像这样:

But with this solution I will be exposing the entire timer which I don't want. How can I pass in a method in the MyAppTimer class which will register the method with the timer's elapsed event internally? Is it something to do with delegates? Maybe something like:

public void RegisterHandler(someStuffGoesHere) //What do I pass in here?
{
  timer.Elapsed += someStuffGoesHere;
}


推荐答案

您可以使用显式访问者:

You can create an event with explicit accessors :

public event EventHandler TimerElapsed
{
    add { timer.Elapsed += value; }
    remove { timer.Elapsed -= value; }
}

您的班级的客户可以直接订阅TimerElapsed事件:

The clients of your class can subscribe directly to the TimerElapsed event :

appTimer.TimerElapsed += SomeHandlerMethod;

如果要使用代码中所示的RegisterHandler方法,则参数的类型应为EventHandler

If you want to use a RegisterHandler method as shown in your code, the type of the parameter should be EventHandler

编辑:请注意,使用这种方法,sender参数的值将是Timer对象,而不是MyAppTimer对象。如果存在问题,则可以执行以下操作:

note that with this approach, the value of sender parameter will be the Timer object, not the MyAppTimer object. If that's a problem, you can do that instead :

public MyAppTimer()
{
    ...
    timer.Elapsed += timer_Elapsed;
}

private void timer_Elapsed(object sender, EventArgs e)
{
    EventHandler handler = this.TimerElapsed;
    if (handler != null)
        handler(this, e);
}

这篇关于注册计时器经过的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆