• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
风拂晚柳
博客园    首页    新随笔    联系   管理    订阅  订阅

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);
        }       
    }
}

 

posted @ 2019-05-20 17:46  风拂晚柳  阅读(21752)  评论(1)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3