不能在子類或外部類發(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最終生成的代碼結構基本一樣,可以知道C#編譯器幫我們做了一些工作。
2、其實C#編譯器應該可以做到允許我們直接調用的,比如:生成的字段為protected類型,考慮到封裝性,編譯器沒這么做,我覺得是合理的。
為什么一定要這么發(fā)布事件(引入一個局部變量):
protected void OnTestEventA()
{
var testEventA = this.TestEventA;
testEventA();
}
相關文章
C#預處理指令之#line,#pragma warning 詳細解析
#line 指令可能由生成過程中的自動中間步驟使用。例如,如果行從原始的源代碼文件中移除,但是您仍希望編譯器基于文件中的原始行號生成輸出,則可以移除行,然后用 #line 模擬原始行號2014-01-01c#利用webmail郵件系統(tǒng)發(fā)送郵件示例分享
在C#中發(fā)送郵件的方式有2種,一種是使用webmail方式進行發(fā)送,另外一種就是采用netmail發(fā)送的方式,這篇文章介紹了c#使用webmail方式發(fā)送郵件示例,大家參考使用吧2014-01-01