1

这是一个来自 msdn 的示例。

public class Timer1
{
    public static void Main()
    {
        System.Timers.Timer aTimer = new System.Timers.Timer();
        aTimer.Elapsed+=new ElapsedEventHandler(OnTimedEvent);
        // Set the Interval to 5 seconds.
        aTimer.Interval=5000;
        aTimer.Enabled=true;

        Console.WriteLine("Press \'q\' to quit the sample.");
        while(Console.Read()!='q');
    }

    // Specify what you want to happen when the Elapsed event is raised.
    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        Console.WriteLine("Hello World!");
    }
}

我的问题针对这一行:

private static void OnTimedEvent(object source, ElapsedEventArgs e)

'source' 和 'e' 变量中隐藏着什么?我知道,它们是函数参数,但是从事件发送给它们的是什么?

4

3 回答 3

2

好吧,source应该是调用事件的任何对象,在这种情况下似乎有些Timer

并且e应该包含更多关于事件的元信息。

例如,如果您有一个on-click事件,它...EventArgs可能会告诉您点击发生的坐标。

如果您使用的是 Visual Studio,则可以键入类似的内容e.,然后智能应该会告诉您其中的所有内容。

于 2013-02-27T16:27:15.843 回答
2

Source 是事件的来源- 在这种情况下是计时器;而 e 包含与事件有关的信息。在这种情况下,ElapsedEventArgs:

http://msdn.microsoft.com/en-us/library/system.timers.elapsedeventargs_members(v=vs.80).aspx

另一个示例是 winforms 中文本框的 keyDown 事件 - e 参数为您提供 KeyCode 并让您确定用户是否在按住 Alt/Control 等。

 txt_KeyDown(object sender, KeyEventArgs e)
 {
   if (e.KeyCode == Keys.Enter)
   ...
于 2013-02-27T16:28:09.240 回答
1

source将成为计时器本身。e将告诉您事件触发的时间:ElapsedEventArgs

大多数时候,您不会关心这些论点中的任何一个。您只关心在触发计时器时做某事,因此您可以愉快地忽略传递给该方法的参数。

于 2013-02-27T16:29:08.647 回答