12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- using System;
- namespace EventDemo1
- {
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("Hello World!");
- EventTest e = new EventTest(); /* 实例化对象,第一次没有触发事件 */
- subscribEvent v = new subscribEvent(); /* 实例化对象 */
- e.ChangeNum += new EventTest.NumManipulationHandler(v.printf); /* 注册 */
- e.SetValue(7);
- e.SetValue(11);
- }
- }
- /***********发布器类***********/
- public class EventTest
- {
- private int value;
- public delegate void NumManipulationHandler( int a );
- public event NumManipulationHandler ChangeNum;
- protected virtual void OnNumChanged(int a)
- {
- if (ChangeNum != null)
- {
- ChangeNum(a); /* 事件被触发 */
- }
- else
- {
- Console.WriteLine("event not fire");
- Console.ReadKey(); /* 回车继续 */
- }
- }
- public EventTest()
- {
- int n = 5;
- SetValue(n);
- }
- public void SetValue(int n)
- {
- if (value != n)
- {
- value = n;
- OnNumChanged(n);
- }
- }
- }
- /***********订阅器类***********/
- public class subscribEvent
- {
- public void printf(int a )
- {
- Console.WriteLine(a+"event fire");
- Console.ReadKey(); /* 回车继续 */
- }
- }
- }
|