一、点击Saywords按钮,直接触发events事件,显示数据
二、开始编辑事件代码,这里造了一个Jiafang的类和一个message(所属Eventargs,即事件参数)的类,用来封装属性
1、Jiafang 的类 namespace 委托与事件Again_and_Again { //造一个甲方的类 public class JiaFang { //给甲方添加成员 private string _Word; public string Word { get { return _Word; } set { _Word = value; } } private string _Name; public string Name { get { return _Name; } set { _Name = value; } } //定义一个事件 public event WeituoHandler events; //定义一个函数来触发这个事件 public void SayWords() { if(events!=null) { events(this, new message() { Word="我是甲方"}); } } } } 2、message的类 namespace 委托与事件Again_and_Again { public class message:EventArgs { private string _Word; public string Word { get { return _Word; } set { _Word = value; } } } } 3、事件 namespace 委托与事件Again_and_Again { //定义一个委托 public delegate void WeituoHandler(object a,message msg); public partial class Form1 : Form { JiaFang x; public Form1() { InitializeComponent(); x = new JiaFang(); x.Name = "甲方"; label1.Text = x.Name; x.events += x_events;//x的点击事件 } void x_events(object a, message msg) { textBox1.Text = "你是谁"; textBox1.Text += " "+msg.Word; } private void button1_Click(object sender, EventArgs e)//Saywords按钮 { x.SayWords();//触发函数,函数用来引发事件 } } }