不能在子類或外部類發(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();不能這樣訪問
}
}
}

分析
1、TestEventA和TestEventB最終生成的代碼結(jié)構(gòu)基本一樣,可以知道C#編譯器幫我們做了一些工作。
2、其實(shí)C#編譯器應(yīng)該可以做到允許我們直接調(diào)用的,比如:生成的字段為protected類型,考慮到封裝性,編譯器沒這么做,我覺得是合理的。
為什么一定要這么發(fā)布事件(引入一個局部變量):
protected void OnTestEventA()
{
var testEventA = this.TestEventA;
testEventA();
}
相關(guān)文章
C#預(yù)處理指令之#line,#pragma warning 詳細(xì)解析
#line 指令可能由生成過程中的自動中間步驟使用。例如,如果行從原始的源代碼文件中移除,但是您仍希望編譯器基于文件中的原始行號生成輸出,則可以移除行,然后用 #line 模擬原始行號2014-01-01C# Process調(diào)用外部程序的實(shí)現(xiàn)
這篇文章主要介紹了C# Process調(diào)用外部程序的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02C#實(shí)現(xiàn)判斷一個時間點(diǎn)是否位于給定時間區(qū)間的方法
這篇文章主要介紹了C#實(shí)現(xiàn)判斷一個時間點(diǎn)是否位于給定時間區(qū)間的方法,涉及C#針對時間的轉(zhuǎn)換與判定相關(guān)技巧,需要的朋友可以參考下2015-08-08c#利用webmail郵件系統(tǒng)發(fā)送郵件示例分享
在C#中發(fā)送郵件的方式有2種,一種是使用webmail方式進(jìn)行發(fā)送,另外一種就是采用netmail發(fā)送的方式,這篇文章介紹了c#使用webmail方式發(fā)送郵件示例,大家參考使用吧2014-01-01