①定义一个要被监视的对象
1 class TestClass 2 { 3 private string value; 4 public string Value 5 { 6 get { return value; } 7 8 set 9 {10 this.value = value;11 Notify();12 }13 }14 15 public event EventHandlerValueChanged;16 17 private void Notify()18 {19 if (ValueChanged != null)20 {21 ValueChanged(this, this);22 }23 }24 25 }
②观察者订阅该事件
1 Program.testClass.ValueChanged += testClass_ValueChanged;
③在事件处理程序中处理相关逻辑
1 this.textBox1.Text = Program.testClass.Value;