Chinaunix首页 | 论坛 | 博客
  • 博客访问: 746638
  • 博文数量: 96
  • 博客积分: 2023
  • 博客等级: 上尉
  • 技术积分: 1738
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-15 10:03
文章分类

全部博文(96)

文章存档

2014年(11)

2012年(85)

分类: 嵌入式

2012-03-16 18:59:25

    一直就对C#的delegate有所耳闻,近阶段看代码时发现很多逻辑都是delegate啊、event的。赶紧对自己充电了,写了些小例子。
    个人理解,delegate类似于C++中的函数指针,而event只是delegate的一个特例,先说一下delegate与event的区别,当我们使用event修饰了delegate声明的函数变量时,我们在类外只能通过+=与-=对此变量进行操作,当然了,类内还是可以使用其他的=操作的;而不用event修饰时,在类外允许我们获得该变量,而且也允许其他在可访问性内的操作。好像使用event修饰的推荐使用void返回值函数。
    很多人可能之前一直对delegate又是+=又是=,以及new运算符的使用有些疑惑,包括我,今天写了小例子试验了下,发现就像我们队字符串操作使用的这些运算符的含义。我们可以使用new也可以不使用。现在贴一下我的代码。

点击(此处)折叠或打开

  1. //delegate声明类

  2. using System;

  3. namespace MarshalTest
  4. {
  5.     class DelegateEvent
  6.     {
  7.         public delegate void msgEvent(string s);
  8.         public event msgEvent msg;
  9.         private void event1(string str)
  10.         {
  11.             Console.WriteLine("event1" + str);
  12.         }
  13.         private void event2(string str)
  14.         {
  15.             Console.WriteLine("event2" + str);
  16.         }

  17.         public void addEvent()
  18.         {
  19.             msg = event1;
  20.             msg += new msgEvent(event1);
  21.             msg += event2;
  22.         }

  23.         public void console()
  24.         {
  25.             msg("haha");
  26.             msg = new msgEvent(event2);
  27.         }
  28.     }
  29. }

  30. //main程序

  31. using System;
  32. using System.Runtime.InteropServices;

  33. namespace MarshalTest
  34. {
  35.     class Program
  36.     {
  37.         static unsafe void Main(string[] args)
  38.         {
  39.             //测试delegate

  40.             DelegateEvent de = new DelegateEvent();
  41.             //de.msg("");

  42.             de.addEvent();
  43.             de.console();
  44.             de.console();
  45.             Console.ReadKey();
  46.         }
  47.     }
  48. }
运行后的结果如下:

阅读(1382) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~