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

C# 外掛架構實作總結:IPlug 介面、自訂屬性與動態載入機制

     編輯:關於C語言

總結與擴充方向

範例刻意簡化以利理解。實務產品可從以下方向強化:

  1. 擴充 IPlug 介面:增加方法、屬性、事件,強化主程式與外掛互動
  2. 允許使用者手動選擇載入哪些外掛

核心程式碼清單

列表一:IPlug 介面

public interface IPlug
{
    IPlugData[] GetData();
    PlugDataEditControl GetEditControl(IPlugData Data);
    bool Save(string Path);
    bool Print(PrintDocument Document);
}

列表二:PlugDisplayNameAttribute

[AttributeUsage(AttributeTargets.Class)]
public class PlugDisplayNameAttribute : System.Attribute
{
    private string _displayName;
    public PlugDisplayNameAttribute(string DisplayName) : base()
    {
        _displayName = DisplayName;
    }
    public override string ToString() { return _displayName; }
}

列表三:EmployeePlug 部分實作

[PlugDisplayName("Employees")]
[PlugDescription("This plug is for managing employee data")]
public class EmployeePlug : System.Object, IPlug
{
    public IPlugData[] GetData()
    {
        return new EmployeeData[]
        {
            new EmployeeData("Jerry", "Seinfeld"),
            new EmployeeData("Bill", "Cosby"),
            new EmployeeData("Martin", "Lawrence")
        };
    }
    public PlugDataEditControl GetEditControl(IPlugData Data)
    {
        return new EmployeeControl((EmployeeData)Data);
    }
    public bool Save(string Path) { /* 實作略 */ }
    public bool Print(PrintDocument Document) { /* 實作略 */ }
}

列表四:LoadPlugs 動態載入方法

private void LoadPlugs()
{
    string[] files = Directory.GetFiles("Plugs", "*.plug");
    foreach (string f in files)
    {
        try
        {
            Assembly a = Assembly.LoadFrom(f);
            foreach (Type type in a.GetTypes())
            {
                if (type.GetInterface("IPlug") != null)
                {
                    if (type.GetCustomAttributes(typeof(PlugDisplayNameAttribute), false).Length != 1)
                        throw new PlugNotValidException(type, "PlugDisplayNameAttribute is not supported");
                    if (type.GetCustomAttributes(typeof(PlugDescriptionAttribute), false).Length != 1)
                        throw new PlugNotValidException(type, "PlugDescriptionAttribute is not supported");
                    _tree.Nodes.Add(new PlugTreeNode(type));
                }
            }
        }
        catch (Exception e) { MessageBox.Show(e.Message); }
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved