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