分享

在C#程序中实现插件架构(3)

 鸿枫nh 2015-11-06

总结

示例程序被设计为尽量的简单,以帮助理解主程序和插件之间的通信.在实际做产品的时候,可以做很多的改进以满足实用要求.比如:

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;
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多