黑马程序员技术交流社区
标题:
不能在子类或外部类发布C#事件代码分析
[打印本页]
作者:
陈君
时间:
2014-9-8 16:56
标题:
不能在子类或外部类发布C#事件代码分析
一个朋友问了一个问题:“为什么不能在子类或外部发布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();不能这样访问
}
}
}
复制代码
081.jpg
(87.42 KB, 下载次数: 11)
下载附件
2014-9-8 16:56 上传
分析
1、TestEventA和TestEventB最终生成的代码结构基本一样,可以知道C#编译器帮我们做了一些工作。
2、其实C#编译器应该可以做到允许我们直接调用的,比如:生成的字段为protected类型,考虑到封装性,编译器没这么做,我觉得是合理的。
为什么一定要这么发布事件(引入一个局部变量):
protected void OnTestEventA()
{
var testEventA = this.TestEventA;
testEventA();
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2