查看: 294|回复: 0

[ASP.NET教程] C#自定义事件之属性改变引发事件示例

发表于 2018-2-10 08:00:07

本文实例为大家分享了C#属性改变引发事件示例的具体代码,供大家参考,具体内容如下

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持程序员之家。

您可能感兴趣的文章:

  • C# 中的动态创建组件(属性及事件)的实现思路及方法


回复

使用道具 举报