zoukankan      html  css  js  c++  java
  • C#学习:事件

            类或对象可以通过事件向其他类或对象通知发生的相关事情。 发送(或引发)事件的类称为“发行者”,接收(或处理)事件的类称为“订阅者”。

    • 一个简单事件实例
          //发行者
          public class Student
          {
              private string name;
      
              //定义一个带参委托
              public delegate void DelegateRegisterFinish(string name);
              //定义一个事件
              public event DelegateRegisterFinish EventRegisterFinish;
      
              public Student(string name)
              {
                  this.name = name;
              }
      
              //在一定条件下,发行者发布事件
              public void Register()
              {
                  Console.WriteLine("学生{0}进行注册", name);
                  if (EventRegisterFinish != null)
                      EventRegisterFinish(name);
              }
          }
          //订阅者
          class RegisterStudent
          {
              static void Main(string[] args)
              {
                  Console.WriteLine("输入学生姓名:");
                  string studentName = Console.ReadLine();
                  Console.WriteLine("--------------------------------------");
      
                  Student student = new Student(studentName);
      
                  //为静态方法student_EventRegisterFinishOne订阅事件
                  //C#1.0语法
                  student.EventRegisterFinish += new
                      Student.DelegateRegisterFinish(student_EventRegisterFinishOne);
                  //C#2.0语法
                  //student.EventRegisterFinish += student_EventRegisterFinishOne;
      
                  //为RegisterStudent实例对象的student_EventRegisterFinishTwo方法订阅事件
                  //本处其实利用多路广播委托为多个方法订阅事件
                  RegisterStudent rs = new RegisterStudent();
                  student.EventRegisterFinish += rs
                      .student_EventRegisterFinishTwo;
      
                  //发行者发布事件后订阅者做相应的操作
                  student.Register();
      
                  Console.WriteLine("--------------------------------------");
                  //取消订阅
                  student.EventRegisterFinish -= rs
                      .student_EventRegisterFinishTwo;
                  student.Register();
      
                  Console.Read();
              }
              private static void student_EventRegisterFinishOne(string name)
              {
                  Console.WriteLine("{0}注册成功", name);
              }
              private void student_EventRegisterFinishTwo(string name)
              {
                  Console.WriteLine("{0}请及时领取住宿用品", name);
              }
          }

      结果:

  • 相关阅读:
    上海社保,统筹内不能转出的疑惑
    c# 代理IP获取通用方法
    element-ui 的el-button组件中添加自定义颜色和图标的实现方法
    前端实现打印功能
    elementUI表格合并单元格
    webpack打包图片资源找不到问题
    Webstorm/IntelliJ Idea 过期破解方法
    ES6 Promise 用法讲解
    移动端开发
    Stylus的基础用法
  • 原文地址:https://www.cnblogs.com/wanghonghu/p/2547045.html
Copyright © 2011-2022 走看看