不能在子類或外部類發(fā)布C#事件代碼分析
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();不能這樣訪問(wèn)
}
}
}
分析
1、TestEventA和TestEventB最終生成的代碼結(jié)構(gòu)基本一樣,可以知道C#編譯器幫我們做了一些工作。
2、其實(shí)C#編譯器應(yīng)該可以做到允許我們直接調(diào)用的,比如:生成的字段為protected類型,考慮到封裝性,編譯器沒(méi)這么做,我覺(jué)得是合理的。
為什么一定要這么發(fā)布事件(引入一個(gè)局部變量):
protected void OnTestEventA()
{
var testEventA = this.TestEventA;
testEventA();
}
相關(guān)文章
C# Email發(fā)送郵件 對(duì)方打開(kāi)郵件可獲得提醒
這篇文章主要為大家詳細(xì)介紹了C# Email發(fā)送郵件功能,對(duì)方打開(kāi)通知你,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-11-11
C#對(duì)WPF數(shù)據(jù)綁定的菜單插入Seperator分隔
這篇文章介紹了C#對(duì)WPF數(shù)據(jù)綁定的菜單插入Seperator分隔的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-06-06
C#調(diào)用Windows的API實(shí)現(xiàn)窗體動(dòng)畫(huà)
在VF、VB、PB的應(yīng)用中,有些無(wú)法通過(guò)語(yǔ)言工具本身來(lái)完成的或者做得不理想的功能,我們會(huì)考慮通過(guò)Windows的API來(lái)完成。本文就來(lái)通過(guò)調(diào)用Windows的API實(shí)現(xiàn)窗體動(dòng)畫(huà),感興趣的可以嘗試一下2022-11-11
C#把數(shù)字轉(zhuǎn)換成大寫(xiě)金額的代碼實(shí)例
這篇文章主要介紹了C#把數(shù)字轉(zhuǎn)換成大寫(xiě)金額的代碼實(shí)例,例如把200轉(zhuǎn)換成“貳佰元”,需要的朋友可以參考下2014-05-05
c#菜單動(dòng)態(tài)合并的實(shí)現(xiàn)方法
這篇文章主要介紹了c#菜單動(dòng)態(tài)合并的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10

