僅套用於屬性(AttributeTargets.Property),建構子接收選單文字與父選單文字,提供可讀寫屬性:
[AttributeUsage(AttributeTargets.Property)]
public class DynamicMenuAttribute : Attribute
{
private string _menuText, _parentText;
public DynamicMenuAttribute(string commandText, string parentText)
{ _menuText = commandText; _parentText = parentText; }
public string MenuText { get => _menuText; set => _menuText = value; }
public string ParentText { get => _parentText; set => _parentText = value; }
}
載入組件後,列舉匯出型別,檢查 CommandHandlerAttribute,具現化並掃描屬性:
foreach (Type t in asm.GetExportedTypes())
{
if (t.GetCustomAttributes(typeof(CommandHandlerAttribute), false).Length > 0)
{
ConstructorInfo ci = t.GetConstructor(Type.EmptyTypes);
if (ci == null) continue;
object obj = ci.Invoke(null);
foreach (PropertyInfo p in t.GetProperties())
{
object[] attrs = p.GetCustomAttributes(typeof(DynamicMenuAttribute), false);
foreach (Attribute at in attrs)
{
DynamicMenuAttribute dym = at as DynamicMenuAttribute;
if (dym != null)
{
MethodInfo mi = p.GetGetMethod();
EventHandler h = mi.Invoke(obj, null) as EventHandler;
UpdateMenu(dym.ParentText, dym.MenuText, h);
}
}
}
}
}
UpdateMenu 負責尋找或建立父選單並加入新選單項。