進一步檢視 MakeGreet 事件生成的代碼:
private GreetingDelegate MakeGreet; // 事件聲明實為私有委托欄位
[MethodImpl(MethodImplOptions.Synchronized)]
public void add_MakeGreet(GreetingDelegate value) {
this.MakeGreet = (GreetingDelegate)Delegate.Combine(this.MakeGreet, value);
}
[MethodImpl(MethodImplOptions.Synchronized)]
public void remove_MakeGreet(GreetingDelegate value) {
this.MakeGreet = (GreetingDelegate)Delegate.Remove(this.MakeGreet, value);
}
明確可見:MakeGreet 確為 GreetingDelegate 類型委托,無論聲明 public 仍編譯為 private。兩方法分別對應 += 與 -=,存取級別取決於事件聲明修飾符。
add_MakeGreet 內部調用 Delegate.Combine 將方法加入委托鏈表。委托本質是類,聲明:
public delegate void GreetingDelegate(string name);
編譯器生成:
public sealed class GreetingDelegate : System.MulticastDelegate {
public GreetingDelegate(object @object, IntPtr method);
public virtual IAsyncResult BeginInvoke(string name, AsyncCallback callback, object @object);
public virtual void EndInvoke(IAsyncResult result);
public virtual void Invoke(string name);
}
深入內容請參閱《CLR Via C#》等專書。