using System;

class MyClass
{
    private int FNum;

    public delegate void MyDelegate(int n); /* 委托是事件的前提 */
    public event MyDelegate MyEvent;        /* 用 event 关键字根据已有的委托声明事件 */

    /* 假如是在给 Num 赋值时触动事件 */
    public int Num 
    {
        get { return FNum; }
        set 
        { 
            FNum = value;
            if (MyEvent != null) MyEvent(FNum);
        }     
    }
}

class Program
{
    static void Main()
    {
        MyClass obj = new MyClass();

        /* 给事件关联上在下面定义的方法: Event_Method */
        obj.MyEvent += new MyClass.MyDelegate(Event_Method);

        obj.Num = 5; /* 会触动事件而写出: 5 是奇数 */
        obj.Num = 6; /* 会触动事件而写出: 6 是偶数 */

        Console.ReadKey();
    }

    /* 这是准备给事件调用的方法 */
    static void Event_Method(int n)
    {
        if (n % 2 == 0) 
            Console.WriteLine("{0} 是偶数", n); 
        else 
            Console.WriteLine("{0} 是奇数", n);
    }
}


相关文章:

  • 2021-05-21
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-25
  • 2021-08-12
  • 2022-01-02
  • 2021-12-19
猜你喜欢
  • 2021-07-14
  • 2021-07-01
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案