委托实现动态时间刷新
1
using System;2
using System.Collections.Generic;3
using System.Runtime.InteropServices;4
using System.Text;5

6
namespace ConsoleApplication67


{8
class Program9

{10
static void Main(string[] args)11

{12
Demo obj = new Demo();13
obj.myEvent+=new Demo.myDelegate(obj_myEvent);14
obj.Run();15
Console.ReadLine();16
}17

18
private static void obj_myEvent(object sender, EventArgs e)19

{20
Console.Write("当前时间:" + DateTime.Now.ToLocalTime());21
}22
}23

24
//事件处理程序委托的标准签名定义一个没有返回值的方法,其第一个参数的类型为 Object,它引用引发事件的实例,25
//第二个参数从 EventArgs 类型派生,它保存事件数据。如果事件不生成事件数据,则第二个参数只是 EventArgs 的一个实例。否则,第二个参数为从 EventArgs 派生的自定义类型,26
//提供保存事件数据所需的全部字段或属性。27

28
class Demo29

{30
public delegate void myDelegate(object sender, EventArgs e);//定义委托31
public event myDelegate myEvent;//定义委托类型的事件32
//定义委托类型的方法33
public void Run()34

{35
//定义一个每一秒钟触发的计时器36
System.Timers.Timer myTimer = new System.Timers.Timer(1000);37
//定义时间间隔所要处理的方法, EventHandler 是一个预定义的委托,专用于表示不生成数据的事件的事件处理程序方法。如果事件生成数据,则必须提供自己的自定义事件数据类型,38
//并且必须要么创建一个委托,其中第二个参数的类型为自定义类型,要么使用泛型 EventHandler 委托类并用自定义类型替代泛型类型参数。39
40
myTimer.Elapsed += new System.Timers.ElapsedEventHandler(TimeEventHandler);41
myTimer.Interval = 1000;42
myTimer.Enabled = true;43
//触发事件44
myEvent(this, new EventArgs());45

46
}47

48
//委托的方法49
public void TimeEventHandler(object sender, System.Timers.ElapsedEventArgs e)50

{51
Console.Clear();52
Console.Write("当前时间:"+ DateTime.Now.ToLocalTime());53
}54
}每天进步一点点... 
浙公网安备 33010602011771号