A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 陈君 金牌黑马   /  2014-8-31 22:46  /  848 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

一个朋友问了一个问题:“为什么不能在子类或外部发布C#事件?”,我说我不知道,要看看生产的IL代码,下面我们看看

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace EventStudy
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. }
  13. }
  14. class Base
  15. {
  16. private Action _testEventB;
  17. public event Action TestEventA;
  18. public event Action TestEventB
  19. {
  20. add
  21. {
  22. _testEventB += value;
  23. }
  24. remove
  25. {
  26. _testEventB -= value;
  27. }
  28. }
  29. protected void OnTestEventA()
  30. {
  31. var testEventA = this.TestEventA;
  32. testEventA();
  33. }
  34. protected void OnTestEventB()
  35. {
  36. var testEventB = _testEventB;
  37. testEventB();
  38. }
  39. }
  40. class Child : Base
  41. {
  42. public void Do()
  43. {
  44. //this.TestEventA();不能这样访问
  45. }
  46. }
  47. }
复制代码

分析
1、TestEventA和TestEventB最终生成的代码结构基本一样,可以知道C#编译器帮我们做了一些工作。
2、其实C#编译器应该可以做到允许我们直接调用的,比如:生成的字段为protected类型,考虑到封装性,编译器没这么做,我觉得是合理的。
为什么一定要这么发布事件(引入一个局部变量):

  1. protected void OnTestEventA()
  2. {
  3. var testEventA = this.TestEventA;
  4. testEventA();
  5. }
复制代码


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马