C#事件的几种处理方式
一、定义事件对象
namespace eventDemo { class Name { private string pName; public delegate void myEventHandler(object sender, NameEventArgs e); public event myEventHandler Get; internal string Text { get { return this.pName; } set { this.pName = value; this.OnGet(new NameEventArgs("text属性被修改了")); } } private void OnGet(NameEventArgs nameEventArgs) { this.Get(this, nameEventArgs); } public override string ToString() { return "Name类的对象"; } } }
二、自定义NameEventArgs类
namespace eventDemo { class NameEventArgs:EventArgs { string pArgs; public NameEventArgs(string s) { pArgs = s; } public override string ToString() { return pArgs; } } }
三、客户端事件的注册
Name name=new Name();
1.直接注册事件
name.Get += new Name.myEventHandler(name_Get); name.Text = "张三";
static void name_Get(object sender, NameEventArgs e) { Console.WriteLine("事件信息:{0}", e.ToString()); Console.WriteLine("事件的发布者:{0}",sender.ToString()); Console.WriteLine("你输入的名字是:{0}", ((Name)sender).Text); }
2.使用匿名方法,直接将方法体的代码和委托对象关联
Name name = new Name(); name.Get += delegate(object sender, NameEventArgs e) { Console.WriteLine("事件信息:{0}", e.ToString()); Console.WriteLine("事件的发布者:{0}", sender.ToString()); Console.WriteLine("你输入的名字是:{0}", ((Name)sender).Text); }; name.Text = "张三";
3.使用lambda表达式
//1、注册事件 //name.Get += new Name.myEventHandler(name_Get); //name.Text = "张三"; //2、匿名方法,直接将方法体的代码和委托对象关联 //Name name = new Name(); //name.Get += delegate(object sender, NameEventArgs e) //{ // Console.WriteLine("事件信息:{0}", e.ToString()); // Console.WriteLine("事件的发布者:{0}", sender.ToString()); // Console.WriteLine("你输入的名字是:{0}", ((Name)sender).Text); //}; //name.Text = "张三"; //3、lambda表达式 name.Get += (object sender, NameEventArgs e) => { Console.WriteLine("事件信息:{0}", e.ToString()); Console.WriteLine("事件的发布者:{0}", sender.ToString()); Console.WriteLine("你输入的名字是:{0}", ((Name)sender).Text); }; name.Text = "张三"; Console.ReadKey();