1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace ConsoleApplication15
7 {
8 class Program
9 {
10 static void Main(string[] args)
11 {
12 Monitor m = new Monitor();
13 m.PropertyChanging += new Monitor.EventHandler(m_PropertyChanging);
14 m.Year = 2014;
15 m.Year = 1890;
16 m.Year = 2013;
17
18 }
19
20 static bool First=false;
21 static void m_PropertyChanging(object sender, PropertyChangingEventArgs e)
22 {
23 if (First==false)
24 {
25 First = true;
26 }
27 else
28 {
29 if (e.NewValue < 1900 || e.NewValue > 3000)
30 e.Cancel = true;
31 }
32 }
33 }
34
35 //(属性正在改变的时候)事件数据
36 class PropertyChangingEventArgs : EventArgs
37 {
38 //构造函数
39 public PropertyChangingEventArgs(string PropertyName, int OldValue, int NewValue)
40 {
41 _PropertyName = PropertyName;
42 _OldValue = OldValue;
43 _NewValue = NewValue;
44 }
45
46 //存储数据
47 private string _PropertyName;
48 private int _OldValue;
49 private int _NewValue;
50 private bool _Cancel;
51
52 //获取或设置属性
53 public string PropertyName
54 {
55 set
56 {
57 _PropertyName = value;
58 }
59 get
60 {
61 return _PropertyName;
62 }
63 }
64 public int OldValue
65 {
66 set
67 {
68 _OldValue = value;
69 }
70 get
71 {
72 return _OldValue;
73 }
74 }
75 public int NewValue
76 {
77 set
78 {
79 _NewValue = value;
80 }
81 get
82 {
83 return _NewValue;
84 }
85 }
86 public bool Cancel
87 {
88 set
89 {
90 _Cancel = value;
91 }
92 get
93 {
94 return _Cancel;
95 }
96 }
97 }
98
99 class Monitor
100 {
101 //定义委托
102 public delegate void EventHandler(object sender, PropertyChangingEventArgs e);
103 //定义事件
104 public event EventHandler PropertyChanging;
105
106 //事件处理(用属性方法)
107 int _YearValue;
108 public int Year
109 {
110 get
111 {
112 return _YearValue;
113 }
114 set
115 {
116 if (_YearValue != value)
117 {
118 if (PropertyChanging != null)
119 {
120 PropertyChangingEventArgs e = new PropertyChangingEventArgs("Year", _YearValue, value);
121 PropertyChanging(this, e);
122 if (e.Cancel)
123 {
124 return;
125 }
126 else
127 {
128 _YearValue = value;
129 }
130 }
131 }
132 }
133 }
134 }
135
136 }