一个朋友问了一个问题:“为什么不能在子类或外部发布C#事件?”,我说我不知道,要看看生产的IL代码,下面我们看看一个朋友问了一个问题:“为什么不能在子类或外部发布C#事件?”,我说我不知道,要看看生产的IL代码,下面我们看看
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace EventStudy
- {
- class Program
- {
- static void Main(string[] args)
- {
- }
- }
- class Base
- {
- private Action _testEventB;
- public event Action TestEventA;
- public event Action TestEventB
- {
- add
- {
- _testEventB += value;
- }
- remove
- {
- _testEventB -= value;
- }
- }
- protected void OnTestEventA()
- {
- var testEventA = this.TestEventA;
- testEventA();
- }
- protected void OnTestEventB()
- {
- var testEventB = _testEventB;
- testEventB();
- }
- }
- class Child : Base
- {
- public void Do()
- {
- //this.TestEventA();不能这样访问
- }
- }
- }
复制代码
分析
1、TestEventA和TestEventB最终生成的代码结构基本一样,可以知道C#编译器帮我们做了一些工作。
2、其实C#编译器应该可以做到允许我们直接调用的,比如:生成的字段为protected类型,考虑到封装性,编译器没这么做,我觉得是合理的。
为什么一定要这么发布事件(引入一个局部变量):
- protected void OnTestEventA()
- {
- var testEventA = this.TestEventA;
- testEventA();
- }
复制代码
|
|