欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#自定义事件之属性改变引发事件示例

程序员文章站 2023-12-02 22:52:46
本文实例为大家分享了c#属性改变引发事件示例的具体代码,供大家参考,具体内容如下 using system; using system.collections....

本文实例为大家分享了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;
      }
     }
    }
   }
  }
 }

}

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