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最終生成的代碼結構基本一樣,可以知道C#編譯器幫我們做了一些工作。
2、其實C#編譯器應該可以做到允許我們直接調用的,比如:生成的字段為protected類型,考慮到封裝性,編譯器沒這么做,我覺得是合理的。
為什么一定要這么發布事件(引入一個局部變量):
testEventA();
}
新聞熱點
疑難解答