手机
当前位置:查字典教程网 >编程开发 >C#教程 >不能在子类或外部类发布C#事件代码分析
不能在子类或外部类发布C#事件代码分析
摘要:复制代码代码如下:usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;...

复制代码 代码如下:

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();不能这样访问

}

}

}

不能在子类或外部类发布C#事件代码分析1

分析

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

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

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

复制代码 代码如下:

protected void OnTestEventA()

{

var testEventA = this.TestEventA;

testEventA();

}

【不能在子类或外部类发布C#事件代码分析】相关文章:

C#截图程序类似腾讯QQ截图实现代码

在C#中创建和读取XML文件的实现方法

C#求解哈夫曼树,实例代码

C#几种获取网页源文件代码的实例

C#中通过API实现的打印类 实例代码

解析C#中用Process类杀死进程,执行命令的深入分析

C#中分部类和分部方法的应用

C#索引器简单实例代码

c# 托盘双击不触发单击事件的实现方法

C# Winform 调用系统接口操作 INI 配置文件的代码

精品推荐
分类导航