zoukankan      html  css  js  c++  java
  • 对C#中事件的简单理解

    对于C#中的事件,我举了个简单的例子来理解事件及其处理。

    这个例子中母亲是事件的发布者,事件是吃饭了。儿子和父亲是事件的订阅者,各自的Eat方法是处理事件的方法。

    下面是详细的加注的例子:

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Threading.Tasks;
     6 using System.IO;
     7 
     8 
     9 /* C#中处理事件采用发布-订阅模型(publisher-subscriber model)
    10  * 包含委托和事件申明的类是发布器
    11  * 包含事件处理的类是订阅器
    12  * 
    13  * C#中申明事件以及事件处理的步骤:
    14  * 1.定义委托和其相关联的事件
    15  * 2.在发布器中写触发事件的条件(方法、其他事件等)
    16  * 3.在订阅器中写处理事件的方法程序
    17  * 4.将事件订阅处理事件的程序,格式是: <事件> += new <与事件关联的委托>( <处理事件的方法名> ) 
    18 */
    19 namespace CsharpStudy
    20 {
    21     //定义一个“母亲”类,是发布器
    22     class Mum {
    23         //与事件关联的委托的定义
    24         public delegate void mydelegate();
    25         //事件的定义
    26         public event mydelegate EatEvent;
    27 
    28         public void Cook() {
    29             Console.WriteLine("母亲:我饭做好了,快来吃饭了...");
    30             //触发事件
    31             EatEvent();
    32         }
    33 
    34     }
    35 
    36     //定义一个“儿子”类,是订阅器
    37     class Son {
    38         //事件处理方法
    39         public void Eat() {
    40             Console.WriteLine("儿子:好,等会,妈,我玩完这局再吃...");
    41         }
    42     }
    43 
    44     //定义一个“父亲”类,是订阅器
    45     class Father {
    46         //事件处理方法
    47         public void Eat() {
    48             Console.WriteLine("父亲:好,老婆,我来吃饭了...");
    49         }
    50     }
    51 
    52 
    53     //主程序类
    54     class Program
    55     {
    56         //程序入口
    57         static void Main(string[] args)
    58         {
    59             /************Main function***************/
    60             //实例化三个类
    61             Mum mun = new Mum();
    62             Father father = new Father();
    63             Son son = new Son();
    64 
    65             //事件订阅方法(订阅son和father的Eat方法)
    66             mun.EatEvent += new Mum.mydelegate(son.Eat);
    67             mun.EatEvent += new Mum.mydelegate(father.Eat);
    68 
    69             mun.Cook();
    70 
    71 
    72             /****************************************/
    73 
    74             Console.ReadKey();
    75         }
    76     }
    77 
    78 
    79 }

    虽然这个例子比较简单,但是能够最粗糙的对事件的发布-订阅模型有个最直观的理解。

  • 相关阅读:
    VS中Debug和Release两个版本的区别
    Activex、OLE、COM、OCX、DLL之间的区别
    解决 C/C++ 程序执行一闪而过的方法
    调用规范stdcall、cdecl、fastcall、thiscall 、naked call的汇编理解
    Windows的MAX_PATH
    Servlet学习笔记(1)
    Eclipse使用JDBC小案例
    Oracle DB 总结(SQL)
    利用JS写一个计算平方的网页
    CSS部分语法1
  • 原文地址:https://www.cnblogs.com/jeavenwong/p/8535758.html
Copyright © 2011-2022 走看看