以 [CommandHandler] 標記類別,[DynamicMenu("命令文字", "父選單")] 標記屬性:
[CommandHandler]
public class CmdHandler
{
[DynamicMenu("Test Command", "Parent Menu")]
public EventHandler CmdFunc
{
get
{
if (theCmdHandler == null)
theCmdHandler = new EventHandler(this.DynamicCommandHandler);
return theCmdHandler;
}
}
private void DynamicCommandHandler(object sender, EventArgs args) { ... }
}
啟動時掃描外掛目錄組件,透過反射尋找標記屬性的類別與屬性,建立選單項:
foreach (Type t in asm.GetExportedTypes())
{
if (t.GetCustomAttributes(typeof(CommandHandlerAttribute), false).Length > 0)
{
var obj = t.GetConstructor(Type.EmptyTypes).Invoke(null);
foreach (PropertyInfo p in t.GetProperties())
{
var attrs = p.GetCustomAttributes(typeof(DynamicMenuAttribute), false);
foreach (Attribute at in attrs)
{
var dym = at as DynamicMenuAttribute;
if (dym != null)
{
var h = p.GetGetMethod().Invoke(obj, null) as EventHandler;
UpdateMenu(dym.ParentText, dym.MenuText, h);
}
}
}
}
}
AttributeUsage 限制套用目標(類別、屬性等),編譯期檢查減少錯誤。善用屬性與反射,可建立動態可配置系統,將責任從開發者移至編譯器,提升可維護性。