首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

Effective C# 原則 42:使用屬性簡化反射 (中)

     編輯:關於C語言

定義 DynamicMenu 屬性類別

僅套用於屬性(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 負責尋找或建立父選單並加入新選單項。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved