C#文法練習(14): 類[六]

來源:互聯網
上載者:User

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);
   }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.