此代码是作为代表和事件的示例提供给我们的。
class AlarmClock {
public Boolean stop;
public delegate void whatToDo(String time);
public event whatToDo customEvent;
public void start() {
new Thread(delegate() {
while (!stop) {
String time = DateTime.Now.ToString("HH:mm:ss tt");
customEvent(time);
Thread.Sleep(1000);
}
}).Start();
}
}
static void Main(string[] args) {
AlarmClock ac = new AlarmClock();
ac.customEvent += delegate(String time) {
if (time.Equals("18:10:00 PM")) {
Console.WriteLine("hello world!");
}
};
ac.customEvent += delegate(String time) {
Console.WriteLine(time);
};
ac.start();
Thread.Sleep(3*60*1000);
ac.stop = true;
Console.ReadKey();
}
我很难理解它,所以我从其他来源了解了委托和事件,但是当我回到这段代码时,我仍然不明白一些事情: 1)第六行中的委托()的目的是什么(new Thread(delegate(){)? 2)如果我有一个委托whatToDo2,线程将如何知道要使用哪个线程? 谢谢!