C#-----事件委托EventHandler的定义与使用
EventHandler表示将处理不包含事件数据的事件的方法
1.声明一个继承EventArgs的子类,传递参数
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EventHandlerExample { public class ClassInfoEventArgs:EventArgs { /// <summary> /// 班级所属年级 /// </summary> public string ClassGrade { get; set; } /// <summary> /// 班级名称 /// </summary> public string ClassName { get; set; } /// <summary> /// 构造方法 /// </summary> /// <param name="ClassGrade"></param> /// <param name="ClassName"></param> public ClassInfoEventArgs(string ClassGrade, string ClassName) { this.ClassGrade = ClassGrade; this.ClassName = ClassName; } } }
2.声明委托对象、执行方法,将方法绑定委托对象
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EventHandlerExample { public class StudentInfo { /// <summary> /// 声明委托对象 /// </summary> public event EventHandler<ClassInfoEventArgs> showStudentInfo; public StudentInfo() { //绑定 showStudentInfo += new EventHandler<ClassInfoEventArgs>(showStudentInfoMethod); } /// <summary> /// 声明一个方法绑定委托 /// </summary> /// <param name="sender"></param> /// <param name="classInfoEvent"></param> public void showStudentInfoMethod(object sender, ClassInfoEventArgs classInfoEvent) { Console.WriteLine("我是" + classInfoEvent.ClassGrade + classInfoEvent.ClassName + "的学生"); } /// <summary> /// 调用方法,开启委托 /// </summary> public void callShowStudentInfo(ClassInfoEventArgs classInfoEvent) { if (showStudentInfo!=null) { showStudentInfo(this, classInfoEvent); } } } }
3.开启EventHandler委托
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EventHandlerExample { class Program { static void Main(string[] args) { ClassInfoEventArgs classInfoEvent = new ClassInfoEventArgs("三年级", "二班"); StudentInfo studentInfo = new StudentInfo(); studentInfo.callShowStudentInfo(classInfoEvent); } } }