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

Effective C# 原則 42:善用屬性簡化反射,建立可擴展的外掛架構

     編輯:關於C#

當必須使用反射時,自訂屬性可大幅降低執行期錯誤風險,將「發現目標」的責任從命名慣例轉移給編譯器與屬性系統。

案例:動態選單命令外掛

需求:啟動時掃描 Addins 目錄組件,自動發現並安裝選單命令處理器。

步驟 1:標記命令處理器類別

[AttributeUsage(AttributeTargets.Class)]
public class CommandHandlerAttribute : Attribute { }

步驟 2:掃描組件並實例化

string addInsDir = Path.Combine(Application.StartupPath, "Addins");
foreach (string dll in Directory.GetFiles(addInsDir, "*.dll")) {
    Assembly asm = Assembly.LoadFrom(dll);
    foreach (Type t in asm.GetExportedTypes()) {
        if (t.GetCustomAttributes(typeof(CommandHandlerAttribute), false).Length > 0) {
            // 找到處理器類別,建立實例...
        }
    }
}

步驟 3:標記命令屬性(含選單文字、父選單)

[AttributeUsage(AttributeTargets.Property)]
public class DynamicMenuAttribute : Attribute {
    public string MenuText { get; set; }
    public string ParentText { get; set; }
    public DynamicMenuAttribute(string cmd, string parent) { MenuText = cmd; ParentText = parent; }
}

步驟 4:掃描屬性並掛載事件


object handlerInstance = Activator.CreateInstance(t);
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 mi = p.GetGetMethod();
            var eh = mi.Invoke(handlerInstance, null) as EventHandler;
            UpdateMenu(dym.ParentText, dym.MenuText, eh);
        }
    }
}

步驟 5:外掛實作範例


[CommandHandler]
public class CmdHandler {
    [DynamicMenu("Test Command", "Parent Menu")]
    public EventHandler CmdFunc {
        get {
            if (_handler == null) _handler = new EventHandler(DynamicCommandHandler);
            return _handler;
        }
    }
    private void DynamicCommandHandler(object sender, EventArgs e) { /* ... */ }
}

屬性的核心價值

  • 宣告運行時意圖,編譯器強制檢查適用目標(AttributeTargets);
  • 攜帶語法/語意資訊(選單文字、父選單等),避免命名慣例解析錯誤;
  • 將「發現」邏輯標準化,減少反射代碼複雜度。

總結

屬性與反射結合,能建立類型安全、易擴展的動態系統。設計屬性類別、限制適用範圍、封裝發現邏輯,是開發外掛架構、工具框架的關鍵技巧。

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