事件是类和对象向外界发出的消息,事件的执行是通过事件委托的方式,调用我们所准备好的处理方法,而是先消息的响应的。要响应某些事件并针对某些事件执行我们自定的方法,需要做到以下几步:
1、声明事件委托。
2、声明事件。
3、添加事件的触发方法。
4、添加事件的处理程序(响应事件的方法)。
5、将指定的事件处理程序邦定到要处理的事件上(订阅事件)。
6、用户信息操作,并触发事件(调用事件的触发方法)。
7、通过事件委托的回调,执行我们需要的事件处理程序。
===============================================================================
一、定义事件源,及其委托
namespace test { public delegate void testEventArgsHandler(object sender, testEventArgs e);//定义委托 public class testEventArgs:EventArgs { private int _a; private int _b; public testEventArgs(int aa,int bb) { _a = aa; _b = bb; } public int a { get { return _a; } set { _a = value; } } public int b { get { return _b; } set { _b = value; } } } }
二、声明事件,添加事件触发方法、添加事件的处理程序(响应事件的方法)
1 public class testclass { 2 public event testEventArgsHandler testEvent;//声明事件 3 public testclass() { 4 5 } 6 //事件出发方法 7 public void Addition(int a, int b) { 8 testEventArgs ts = new testEventArgs(a,b); 9 if (testEvent !=null) 10 { 11 testEvent(this, ts); 12 } 13 } 14 }
三、将指定的事件处理程序邦定到要处理的事件上(订阅事件)。
用户信息操作,并触发事件(调用事件的触发方法)。
通过事件委托的回调,执行我们需要的事件处理程序。
1 public partial class Form1 : Form 2 { 3 4 testclass tc = new testclass(); 5 public Form1() 6 { 7 InitializeComponent(); 8 //订阅事件 9 tc.testEvent += new testEventArgsHandler(tc_testEvent); 10 } 11 //事件委托的回调 12 void tc_testEvent(object sender, testEventArgs e) 13 { 14 textBox3.Text = (e.a + e.b).ToString(); 15 } 16 //调用事件的触发方法 17 private void button1_Click(object sender, EventArgs e) 18 { 19 try 20 { 21 int a = int.Parse(textBox1.Text); 22 int b = int.Parse(textBox2.Text); 23 tc.Addition(a, b); 24 } 25 catch (Exception ex) 26 { 27 MessageBox.Show("错误---" + ex.Message); 28 } 29 } 30 }
浙公网安备 33010602011771号