建立動態可配置系統時,為自有型別、方法、屬性定義自訂屬性,可標示執行意圖、簡化反射查找、減少型別錯誤。
主程式需掃描 Addins 目錄下組件,發現並安裝命令處理器。步驟:
Assembly.LoadFrom 載入組件。
[AttributeUsage(AttributeTargets.Class)]
public class CommandHandlerAttribute : Attribute
{
public CommandHandlerAttribute() { }
}
AttributeUsage 限制僅能套用於類別。透過 GetCustomAttributes 快速篩選候選型別:
foreach (string file in Directory.GetFiles(addInsDir, "*.dll"))
{
Assembly asm = Assembly.LoadFrom(file);
foreach (Type t in asm.GetExportedTypes())
{
if (t.GetCustomAttributes(typeof(CommandHandlerAttribute), false).Length > 0)
{
// 發現命令處理器型別,進行配置與安裝
}
}
}
屬性讓原本複雜的反射邏輯變得清晰、安全。