自行實作 Hashtable _eventList + static object _key 模式雖省記憶體,但 .NET Framework 已內建更完善的 Component.Events (EventHandlerList) 機制:
public class Component1 : Component
{
private static readonly object _processStartKey = new object();
public event EventHandler ProcessStart
{
add { Events.AddHandler(_processStartKey, value); }
remove { Events.RemoveHandler(_processStartKey, value); }
}
protected virtual void OnProcessStart()
{
EventHandler handler = (EventHandler)Events[_processStartKey];
handler?.Invoke(this, EventArgs.Empty);
}
}
Component 即可使用 Events 屬性EventHandlerList 內部為單向鏈結串列,未訂閱事件時**零記憶體開銷**add/remove 存取器模式,相容設計工具與序列化C# 純物件導向,**不允許全域函式/變數**,建議以 sealed + private constructor + static members 封裝常用工具方法:
public sealed class DomainHelper
{
public static string GetCurrentDomainDir()
=> AppDomain.CurrentDomain.BaseDirectory;
private DomainHelper() { } // 防止實例化
}
// 使用
MessageBox.Show(DomainHelper.GetCurrentDomainDir());
sealed + private ctor 強制靜態使用此模式在元件設計中極常見 (如 Path、Environment、Directory 等 BCL 類別皆為靜態工具類)。