總結
示例程序被設計為盡量的簡單,以幫助理解主程序和插件之間的通信.在實際做產品的時候,可以做很多的改進以滿足實用要求.比如:
1.通過對IPlug接口增加更多的方法,屬性,事件,可以增加主程序和插件之間的通信點.兩者間的更多的交互操作使得插件可以做更多的事情.
2.可以允許用戶主動選擇需要加載的插件.
圖片一:
列表一:The IPlug interface
public interface IPlug
{
IPlugData[] GetData();
PlugDataEditControl GetEditControl(IPlugData Data);
bool Save(string Path);
bool Print(PrintDocument Document);
}列表二:The PlugDisplayNameAttribute class definition
[AttributeUsage(AttributeTargets.Class)]
public class PlugDisplayNameAttribute : System.Attribute
{
private string _displayName;
public PlugDisplayNameAttribute(string DisplayName) : base()
{
_displayName=DisplayName;
return;
}
public override string ToString()
{
return _displayName;
}
列表三:A partial listing of the EmployeePlug class definition
[PlugDisplayName("Employees")]
[PlugDescription("This plug is for managing employee data")]
public class EmployeePlug : System.Object, IPlug
{
public IPlugData[] GetData()
{
IPlugData[] data = new EmployeeData[]
{
new EmployeeData("Jerry", "Seinfeld")
,new EmployeeData("Bill", "Cosby")
,new EmployeeData("Martin", "Lawrence")
};
return data;
}
public PlugDataEditControl GetEditControl(IPlugData Data)
{
return new EmployeeControl((EmployeeData)Data);
}
public bool Save(string Path)
{
//implementation not shown
}
public bool Print(PrintDocument Document)
{
//implementation not shown
}
}
列表四:The method LoadPlugs
private void LoadPlugs()
{
string[] files = Directory.GetFiles("Plugs", "*.plug");
foreach(string f in files)
{
try
{
Assembly a = Assembly.LoadFrom(f);
System.Type[] types = a.GetTypes();
foreach(System.Type type in types)
{
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);
}
}
return;
}