源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2022-03-02 12:47 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:不能在子类或外部类发布C#事件代码分析
[u]复制代码[/u] 代码如下:
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();不能这样访问         }     } }
[img]http://files.jb51.net/file_images/article/201311/20131125102256.jpg?20131025102712[/img] 分析 1、TestEventA和TestEventB最终生成的代码结构基本一样,可以知道C#编译器帮我们做了一些工作。 2、其实C#编译器应该可以做到允许我们直接调用的,比如:生成的字段为protected类型,考虑到封装性,编译器没这么做,我觉得是合理的。 为什么一定要这么发布事件(引入一个局部变量):
[u]复制代码[/u] 代码如下:
protected void OnTestEventA()         {             var testEventA = this.TestEventA;             testEventA();         }
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部