C#自定義事件之屬性改變引發(fā)事件示例
更新時(shí)間:2017年07月13日 11:28:55 作者:cnc
這篇文章主要為大家詳細(xì)介紹了C#自定義事件之屬性改變引發(fā)事件示例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
本文實(shí)例為大家分享了C#屬性改變引發(fā)事件示例的具體代碼,供大家參考,具體內(nèi)容如下
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;
}
}
}
//(屬性正在改變的時(shí)候)事件數(shù)據(jù)
class PropertyChangingEventArgs : EventArgs
{
//構(gòu)造函數(shù)
public PropertyChangingEventArgs(string PropertyName, int OldValue, int NewValue)
{
_PropertyName = PropertyName;
_OldValue = OldValue;
_NewValue = NewValue;
}
//存儲數(shù)據(jù)
private string _PropertyName;
private int _OldValue;
private int _NewValue;
private bool _Cancel;
//獲取或設(shè)置屬性
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;
}
}
}
}
}
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
WPF利用LiveCharts實(shí)現(xiàn)動態(tài)曲線圖繪制
LiveCharts是一個(gè)比較漂亮的WPF圖表控件,在數(shù)據(jù)發(fā)生變化后,還可以設(shè)置相對于的動畫效果,本文就來利用LiveCharts繪制簡單的動態(tài)曲線圖吧2023-10-10
C++聯(lián)合體轉(zhuǎn)換成C#結(jié)構(gòu)的實(shí)現(xiàn)方法
這篇文章主要介紹了C++聯(lián)合體轉(zhuǎn)換成C#結(jié)構(gòu)的實(shí)現(xiàn)方法,需要的朋友可以參考下2014-08-08
unity實(shí)現(xiàn)場景切換進(jìn)度條顯示
這篇文章主要為大家詳細(xì)介紹了unity實(shí)現(xiàn)場景切換進(jìn)度條顯示,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-11-11
一種c#深拷貝方式完勝java深拷貝(實(shí)現(xiàn)上的對比分析)
下面小編就為大家?guī)硪黄环Nc#深拷貝方式完勝java深拷貝(實(shí)現(xiàn)上的對比分析)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-07-07

