[C#] C#中声明、调用和配置事件的演示代码 →→→→→进入此内容的聊天室

来自 , 2020-08-12, 写在 C#, 查看 142 次.
URL http://www.code666.cn/view/7230b2b0
  1. // events1.cs
  2. using System;
  3. namespace MyCollections
  4. {
  5.    using System.Collections;
  6.  
  7.    // 用于对更改通知进行挂钩的委托类型。
  8.    public delegate void ChangedEventHandler(object sender, EventArgs e);
  9.  
  10.    // 一个类,其作用与 ArrayList 类似,
  11.    // 但在每次列表更改时发送通知。
  12.    public class ListWithChangedEvent: ArrayList
  13.    {
  14.       // 一个事件,每当列表元素更改时,客户端可利用该事件
  15.       // 获得通知。
  16.       public event ChangedEventHandler Changed;
  17.  
  18.       // 调用 Changed 事件;每当列表更改时调用
  19.       protected virtual void OnChanged(EventArgs e)
  20.       {
  21.          if (Changed != null)
  22.             Changed(this, e);
  23.       }
  24.  
  25.       // 重写可更改列表的某些方法;
  26.       // 在每个重写后调用事件
  27.       public override int Add(object value)
  28.       {
  29.          int i = base.Add(value);
  30.          OnChanged(EventArgs.Empty);
  31.          return i;
  32.       }
  33.  
  34.       public override void Clear()
  35.       {
  36.          base.Clear();
  37.          OnChanged(EventArgs.Empty);
  38.       }
  39.  
  40.       public override object this[int index]
  41.       {
  42.          set
  43.          {
  44.             base[index] = value;
  45.             OnChanged(EventArgs.Empty);
  46.          }
  47.       }
  48.    }
  49. }
  50.  
  51. namespace TestEvents
  52. {
  53.    using MyCollections;
  54.  
  55.    class EventListener
  56.    {
  57.       private ListWithChangedEvent List;
  58.  
  59.       public EventListener(ListWithChangedEvent list)
  60.       {
  61.          List = list;
  62.          // 将“ListChanged”添加到“List”中的 Changed 事件。
  63.          List.Changed += new ChangedEventHandler(ListChanged);
  64.       }
  65.  
  66.       // 每当列表更改时就会进行以下调用。
  67.       private void ListChanged(object sender, EventArgs e)
  68.       {
  69.          Console.WriteLine("This is called when the event fires.");
  70.       }
  71.  
  72.       public void Detach()
  73.       {
  74.          // 分离事件并删除列表
  75.          List.Changed -= new ChangedEventHandler(ListChanged);
  76.          List = null;
  77.       }
  78.    }
  79.  
  80.    class Test
  81.    {
  82.       // 测试 ListWithChangedEvent 类。
  83.       public static void Main()
  84.       {
  85.       // 创建新列表。
  86.       ListWithChangedEvent list = new ListWithChangedEvent();
  87.  
  88.       // 创建一个类,用于侦听列表的更改事件。
  89.       EventListener listener = new EventListener(list);
  90.  
  91.       // 在列表中添加和移除项。
  92.       list.Add("item 1");
  93.       list.Clear();
  94.       listener.Detach();
  95.       }
  96.    }
  97. }
  98.  
  99.  
  100.  
  101.  
  102. //csharp/4912

回复 "C#中声明、调用和配置事件的演示代码"

这儿你可以回复上面这条便签

captcha