首页 > 代码库 > 委托与事件
委托与事件
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace 委托实现事件1 7 { 8 class Program 9 { 10 static void Main(string[] args) 11 { 12 Counter c = new Counter(); 13 //告诉Counter:当数到10的倍数的时候请调用_On10 14 c.On10 = _On10;//相当于一个事件,指向一个方法 15 //c.On10 = _On102; 16 //c.On10 =c.On10 + _On102;//可以多个人同时听了 17 // c.On10 += _On102; 18 while (true)//是一个死循环,一直执行 19 { 20 c.Next(); 21 } 22 Console.ReadKey(); 23 } 24 25 //value怎么传过来Counter使用者不用关心 26 static void _On10(int value) 27 { 28 Console.WriteLine("10的倍数:"+value); 29 } 30 31 //value怎么传过来Counter使用者不用关心 32 static void _On102(int value) 33 { 34 Console.WriteLine("我也听到了10的倍数:" + value); 35 } 36 } 37 38 class Counter 39 { 40 public OnCountDelegate On10;//把委托对象声明为一个字段 41 42 private int i=0; 43 44 public void Next() 45 { 46 i++; 47 if (i % 10 == 0) 48 { 49 if (On10 != null) 50 { 51 //解耦:解除耦合。两边都是“糊涂”! 52 //不用关心到底指向谁,调用就行 53 On10(i);//调用On10指向的函数,相当于把事件通知出去 54 } 55 } 56 } 57 } 58 59 delegate void OnCountDelegate(int value); 60 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。