本文實例為大家分享了C#屬性改變引發事件示例的具體代碼,供大家參考,具體內容如下
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;      }     }    }   }  } }}以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答