委託實現動態時間重新整理

來源:互聯網
上載者:User

 

class
 1using System;
 2using System.Collections.Generic;
 3using System.Runtime.InteropServices;
 4using System.Text;
 5
 6namespace ConsoleApplication6
 7{
 8    class Program
 9    {
10        static void Main(string[] args)
11        {
12            Demo obj = new Demo();
13            obj.myEvent+=new Demo.myDelegate(obj_myEvent);
14            obj.Run();
15            Console.ReadLine();
16        }
17
18        private static void obj_myEvent(object sender, EventArgs e)
19        {
20            Console.Write("目前時間:" + DateTime.Now.ToLocalTime());
21        }
22    }
23
24    //事件處理常式委託的標準簽名定義一個沒有傳回值的方法,其第一個參數的類型為 Object,它引用引發事件的執行個體,
25    //第二個參數從 EventArgs 類型派生,它儲存事件數目據。如果事件不建置事件資料,則第二個參數只是 EventArgs 的一個執行個體。否則,第二個參數為從 EventArgs 派生的自訂類型,
26    //提供儲存事件數目據所需的全部欄位或屬性。
27
28    class Demo
29    {
30        public delegate void myDelegate(object sender, EventArgs e);//定義委託
31        public event myDelegate myEvent;//定義委託類型的事件
32        //定義委託類型的方法
33        public void Run()
34        {
35            //定義一個每一秒鐘觸發的計時器
36            System.Timers.Timer myTimer = new System.Timers.Timer(1000);
37            //定義時間間隔所要處理的方法, EventHandler 是一個預定義的委託,專用於表示不產生資料的事件的事件處理常式方法。如果事件產生資料,則必須提供自己的自訂事件數目據類型,
38            //並且必須要麼建立一個委託,其中第二個參數的類型為自訂類型,要麼使用泛型 EventHandler 委託類並用自訂類型替代泛型型別參數。
39            
40            myTimer.Elapsed += new System.Timers.ElapsedEventHandler(TimeEventHandler);
41            myTimer.Interval = 1000;
42            myTimer.Enabled = true;
43            //觸發事件
44            myEvent(this, new EventArgs());
45
46        }
47
48        //委託的方法
49        public void TimeEventHandler(object sender, System.Timers.ElapsedEventArgs e)
50        {
51            Console.Clear();
52            Console.Write("目前時間:"+ DateTime.Now.ToLocalTime());
53        }
54    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.