亲宝软件园·资讯

展开

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

cnc 人气:0
想了解C#自定义事件之属性改变引发事件示例的相关内容吗,cnc在本文为您仔细讲解C#属性改变引发事件示例的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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;
      }
     }
    }
   }
  }
 }

}

加载全部内容

相关教程
猜你喜欢
用户评论