.NET:为什么不能在子类或外部发布C#事件

背景

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

测试

代码

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

IL

分析

1、TestEventA和TestEventB最终生成的代码结构基本一样,可以知道C#编译器帮我们做了一些工作。

2、其实C#编译器应该可以做到允许我们直接调用的,比如:生成的字段为protected类型,考虑到封装性,编译器没这么做,我觉得是合理的。

一则笑话

一位老先生问我如何拷贝文件,我说Control+C,然后Control+V,第二天他告诉我不行,后来发现他是在公司Control+C,回到家里Control+V的。

今天发生了真人版的这个事情,一位非常有前途的兄弟,在一个基类里定义了一个Event,有两个子类,分别为A和B,在A的实例里发布Event,在B的实例里监听这个Event。

一个问题

为什么一定要这么发布事件(引入一个局部变量):

1         protected void OnTestEventA()
2         {
3             var testEventA = this.TestEventA;
4 
5             testEventA();
6         }

背景

找个机会得看看一些C#本质之类的书了,很多概念我也不是很清楚!

 

posted on 2013-07-19 00:09  幸福框架  阅读(2138)  评论(17编辑  收藏  举报

导航

我要啦免费统计