//发布事件 public void OnMarriageComing(string msg) { if (MarryEvent != null) { MarryEvent.Invoke(msg); } }
public event EventHandler MarryEvent; // II. 用.NET类库中预定义的委托类型EventHandler来定义事件 // 5. 调用委托变量,发出事件(消息发出者) public void OnMarriageComing(string msg) { //MarryEvent?.Invoke(msg); //MarryEvent?.Invoke(this, new EventArgs()); // II. 用.NET类库中预定义的委托类型EventHandler来定义事件 MarryEvent?.Invoke(msg, new EventArgs()); // II. 也可以把sender换成msg,用来传递数据,不过一般都是用new EventArgs()传递数据,见下一个例子 }
public virtual void BeMarried(People people) { MarryArgs e = new MarryArgs { T = people }; if (PreviousMate.Count == 0 && CurrentMate.Count == 1 && people.PreviousMate.Count == 0 && people.CurrentMate.Count == 1 && CurrentMate[CurrentMate.Count - 1] == people) { e.Tip = "从一而终,矢志不渝!"; MarryEvent?.Invoke(this, e); } else { var curIndex = CurrentMate.FindIndex((t) => t.Equals(people)); var preIndex = PreviousMate.FindIndex((t) => t.Equals(people)); if (curIndex == -1 && preIndex == -1) { e.Tip = "我结婚了,新郎(娘)不是他!"; MarryEvent?.Invoke(this, e); } else if (curIndex == CurrentMate.Count - 1) { e.Tip = "执子之手,与子偕老!"; MarryEvent?.Invoke(this, e); } else if (preIndex != -1 || curIndex != -1) { e.Tip = "破镜也能重圆!"; MarryEvent?.Invoke(this, e); } } Couple = people; people.Couple = this; }
// 5. 调用委托,激活事件(消息发出者,事件发布者)发出通知 public void OnBirthdayCom(string msg) { MarryEvent?.Invoke(this, new MarryEventArgs(msg)); }