public void TimeUp() { //生日到了,触发事件 BirthdayEventArgs eventArgs = new BirthdayEventArgs("fwq"); this.Notify(eventArgs); }
public bool CheckKeys(string keys) { if (keys == "fwq123") { BirthdayEventArgs eventArgs = new BirthdayEventArgs("隐藏密钥输入成功!"); this.NotifyKeys(eventArgs); return(true); } return(false); }
// 第三步:定义一个负责触发事件的方法,它通知已关注的对象(通知我的好友) protected virtual void Notify(BirthdayEventArgs e) { // 出于线程安全的考虑,现在将对委托字段的引用复制到一个临时字段中 BirthDayEventHandle temp = Interlocked.CompareExchange(ref BirthDayEvent, null, null); if (temp != null) { // 触发事件,与方法的使用方式相同 // 事件通知委托对象,委托对象调用封装的方法 temp(this, e); } }
protected virtual void NotifyKeys(BirthdayEventArgs e) { // 出于线程安全的考虑,现在将对委托字段的引用复制到一个临时字段中 Interlocked.CompareExchange(ref InputKeysEvent, null, null)?.Invoke(this, e); }
public void BuyCake(object sender, BirthdayEventArgs e) { Console.WriteLine(e.Name + " 生日到了,我要准备买蛋糕"); }
//生日事件处理方法 public void SendGift(object sender, BirthdayEventArgs e) { Console.WriteLine(e.Name + " 生日到了,我要送礼物"); }
static void HappyBirthday(object sender, BirthdayEventArgs e) { //sender is the Person, and it has event arguments Console.WriteLine(e.Message); }