C# Event

來源:互聯網
上載者:User

在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一個event13         public event myEventHandler valueChanged;14 15         public string Val            //建立一個property,為了expose theValue16         {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 Program26     {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             do34             {35                 str = Console.ReadLine();36                 if (!str.Equals("exit"))37                     myEvt.Val = str;        //trigger the Event38 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 }

 

 

 

 

聯繫我們

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