zoukankan      html  css  js  c++  java
  • 关于C#事件总结与应用

    C#事件总结与应用

    什么是事件

    事件是特殊化的委托,委托是事件的基础,所以在介绍事件之前先介绍一下委托

    通俗的说就是

    事件就是消息驱动器通过委托类来调用感兴趣的方法,事实上事件调用是间接的调用  就像是显示中我的代理人一样

    发布者与订阅者

    在学习事件的时候们首先要明白什么是发布者什么是订阅者:

    通知某件事情发生的,就是发布者(例如我发布了微博)

    对某件事情关注的,就是订阅者(例如我关注了微博)

    事件触发和注册

    事件发生时,会通知所有关注该事件的订阅者(例如我发布了新的微博)

    想在事件发生时被通知,就必须注册表示关注(例如我关注微博有了新的动态)

    事件的声明

    事件的声明首先要先定义一个委托类 ,因为事件的触发就是调用一系列订阅者注册函数的过程 而委托本身就可以持有多个签名返回值相同的函数

    事件的声明的关键字:event

    笔者在这里写了一个关于学校上下课的事件

     

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    using System.Threading.Tasks;

     

    namespace 事件

    {

        public delegate void EventHandler(int ringKind);//声明一个带参数的委托

        public class ShoolRing //定义一个发布者类

     

        {

     

            public event EventHandler OnBellSound;//委托发布

            public void Jow(int ringKind)//实现打铃操作

            {

                if (ringKind == 1 || ringKind == 2)//判断打铃是否合法

                {

                    Console.Write(ringKind == 1 ? "上课铃响了," : "下课铃响了 ,");

                    if (OnBellSound != null)//如果委托事件不等于空则回调委托所定义的方法

                    {

     

                        OnBellSound(ringKind);

                    }

                }

                else

                {

                    Console.WriteLine(" 这个铃声参数不正确!");

              

                }

            }

     

     

        }

        public class Studens

        {

           

     

     

            public void ShowJow(int ringKind)//学生方法

            {

                if (ringKind == 1)

                {

                    Console.WriteLine("同学们去上课!");

                }

                else if (ringKind == 2)

                {

                    Console.WriteLine("同学们课间休息了!");

                }

            }

    }

    }

    class Program

        {

            static void Main(string[] args)

            {

                ShoolRing shool = new ShoolRing();//实例化发布者类

     

                Studens stu = new Studens();//实例化订阅者类

                shool.OnBellSound += stu.ShowJow;//订阅事件

             

     

                shool.Jow(Convert.ToInt32(Console.ReadLine()));

                Console.ReadLine();

         

     

     

     

            }

        }

    }

     

  • 相关阅读:
    Windows下使用nmake编译C/C++的makefile
    poj 1228
    poj 1039
    poj 1410
    poj 3304
    poj 1113
    poj 2074
    uva 1423 LA 4255
    poj 1584
    poj 3277
  • 原文地址:https://www.cnblogs.com/qufeiba/p/6901539.html
Copyright © 2011-2022 走看看