科技行者

行者学院 转型私董会 科技行者专题报道 网红大战科技行者

知识库

知识库 安全导航

至顶网软件频道基础软件在C#程序中实现插件架构

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

  • 扫一扫
    分享文章到微信

  • 扫一扫
    关注官方公众号
    至顶头条

这篇文章将讲述如何利用这些奇妙的特性,用插件(plug-ins)机制建立可扩展的解决方案

作者:Sunmast翻译 来源:论坛 2007年11月13日

关键字:

  • 评论
  • 分享微博
  • 分享邮件
源代码

  示例程序的完整的源代码可以在这里下载.

ftp://ftp.cuj.com/pub/2003/2101/walchesk.zip

  图片一:


  列表一: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;
}

查看本文来源

    • 评论
    • 分享微博
    • 分享邮件
    邮件订阅

    如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。

    重磅专题
    往期文章
    最新文章