zoukankan      html  css  js  c++  java
  • C# Event

    在C#建立Event有5步

    一: 最外面声明Delegate:

    delegate void MyEventHandler (int x, string y);

    二:建立含有私有类的Event(被别人使用):

    class MyClass()

    {

      ...

      public event MyEventHandler MyEvent;  

      ...

    }

    三:建立class的实例(Subscribing to an event)

    MyClass obj = new MyClass();

    四:Listening to the event:

    subscribe event: obj.MyEvent += handlerFunction;

    stop listing:     obj.MyEvent -= handlerFunction;

     

    五:Declare the function:注意要和delegate一致:

    void handlerFunction(int x, string y) { ... }

    This is the function taht's going to be called whenever that event happens

     

    实例:

    View Code
     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 
     6 namespace UsingEvent
     7 {
     8     public delegate void myEventHandler(string newValue);
     9     
    10     class EventExample    //建立一个可以raise evnent的class,其他人可以用.因为是private的class所以外部使用需要一个
    11     {
    12         private string theValue;        //建立一个theValue,目的是一旦value变了就raise一个event
    13         public event myEventHandler valueChanged;
    14 
    15         public string Val            //建立一个property,为了expose theValue
    16         {
    17             set            
    18             {
    19                 this.theValue = value;                    //赋值给内部theValue为外部付给property的任何值
    20                 this.valueChanged(theValue);        //任何本class的实例subscribe to listening this event的会被告知value change了
    21             }
    22         }
    23     }
    24 
    25     class Program
    26     {
    27         static void Main(string[] args)
    28         {
    29             EventExample myEvt = new EventExample();        //新建含有Event的EventExample类的实例
    30             myEvt.valueChanged += new myEventHandler(myEvt_valueChanged);        //加载一个myEvt_valueChanged function给实例的event,这个会被IDE创建
    31 
    32             string str;
    33             do
    34             {
    35                 str = Console.ReadLine();
    36                 if (!str.Equals("exit"))
    37                     myEvt.Val = str;        //trigger the Event
    38 
    39             } while (!str.Equals("exit"));
    40         }
    41 
    42         static void myEvt_valueChanged(string newValue)        //这个会被IDE创建,创建的newValue和之前delegate的参数一样
    43         {
    44             Console.WriteLine("The value changed to {0}", newValue);
    45         }
    46     }
    47 }

     

     

  • 相关阅读:
    超级女声杭州赛区7进5
    究竟怎么了?
    最近发现
    S2SH基于角色权限拦截
    基于S2SH的电子商务网站系统性能优化
    TSQL复习笔记(一)
    用户sa登录失败,该用户与可信sql server连接无关联
    SQL附加数据库报5120的错误的解决办法
    DotNet中配置文件的使用(一)
    JQuery中使用AJAX $.ajax(prop)方法详解
  • 原文地址:https://www.cnblogs.com/shawnzxx/p/2664697.html
Copyright © 2011-2022 走看看