不能在子類或外部類發(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、其實C#編譯器應(yīng)該可以做到允許我們直接調(diào)用的,比如:生成的字段為protected類型,考慮到封裝性,編譯器沒這么做,我覺得是合理的。
為什么一定要這么發(fā)布事件(引入一個局部變量):
protected void OnTestEventA()
{
var testEventA = this.TestEventA;
testEventA();
}
相關(guān)文章
C#對WPF數(shù)據(jù)綁定的菜單插入Seperator分隔
這篇文章介紹了C#對WPF數(shù)據(jù)綁定的菜單插入Seperator分隔的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-06-06
C#調(diào)用Windows的API實現(xiàn)窗體動畫
在VF、VB、PB的應(yīng)用中,有些無法通過語言工具本身來完成的或者做得不理想的功能,我們會考慮通過Windows的API來完成。本文就來通過調(diào)用Windows的API實現(xiàn)窗體動畫,感興趣的可以嘗試一下2022-11-11

