手机
当前位置:查字典教程网 >编程开发 >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#中创建和读取XML文件的实现方法

c#初学简单程序实例代码介绍

C# L型棋牌覆盖实现代码与效果

解决C#全屏幕截图的实现方法

你是不是这样写异常处理代码的呢?

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

c# 可疑文件扫描代码(找到木马)(简)

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

C#中判断某类型是否可以进行隐式类型转换

C#中实现任意List的全组合算法代码

精品推荐
分类导航