c#中实现当一个类实例的属性值改变时,触发事件调用另一个方法

using System; 

namespace ConsoleApplication
{ 
class Program 
{ 
static void Main(string[] args) 
{ 
people p = new people("Name1"); 
p.PropertyChanged += new EventHandler(p_PropertyChanged);//注册事件处理函数 
p.Name = "Name2"; 
Console.ReadKey(); 
} 

static void p_PropertyChanged(object sender, EventArgs e)//事件的处理函数 
{ 
Console.WriteLine("NamePropertyChanged:"+(sender as people).Name); 
} 
} 
class people 
{ 
//事件名
public event EventHandler PropertyChanged; private string name=String .Empty; public people(string name) { this.name = name; } public string Name { get { return name; } set { name = value; this.OnPropertyChanged(new EventArgs());//每次改变Name值调用方法; } } private void OnPropertyChanged(EventArgs eventArgs) { if (this.PropertyChanged != null)//判断事件是否有处理函数 { this.PropertyChanged(this, eventArgs); } } } }

如上面的代码实例可知,当name属性变化时,触发了PropertyChanged事件,开发人员就可以在调用此类时,当name属性发生改变时,做相应的处理。

posted @ 2012-11-09 09:17  心平_气和  阅读(6611)  评论(0编辑  收藏  举报