博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

初探反射(三)之插件开发

Posted on 2010-12-03 14:45  Mr.X  阅读(2685)  评论(17编辑  收藏  举报

今天我们来说说插件的开发。首先我们来看看下面这段代码:

 

namespace XylF
{
public interface Cs
{
void DoIt();
}


[AttributeUsage(AttributeTargets.Class
|AttributeTargets.Struct,Inherited=false)]
public sealed class XylAttribute :Attribute
{
private string msg;

public string Msg
{
get { return msg; }
set { msg = value; }
}
public XylAttribute()
{ }

public XylAttribute(string msg)
{
this.msg = msg;
}

}
}

 

这里我们创建了一个接口 这个接口表示插件需要去实现里面的方法,接口本身是什么作用的 它在这里就是一个契约,插件需要去遵循它。

然后我们看看插件是怎么写的:

 

namespace Lz
{

[Xyl(Msg
= "Edit by Xyl")]
public class Lzs:Cs
{

public void DoIt()
{
Console.WriteLine(
"this is c#");
}
}
}

 

我们在插件里面引入XylF的程序集 然后继承Cs接口 实现接口里面的方法(插件遵循接口给出的契约)这里为了方便,方法只输出一句话。有了约束和插件 我们来看看主程序怎么写:

 

static void Main(string[] args)
{

Console.WriteLine(
"请输入插件名称");
string path = Console.ReadLine();
Assembly asm
= null;
try
{
asm
= Assembly.Load(path);

}
catch (FileNotFoundException e)
{
Console.WriteLine(e.Message);
}
var sm
= from c in asm.GetTypes() where c.IsClass&&((c.GetInterface("Cs")!=null)) select c;

foreach (Type t in sm)
{
Cs ts
= (Cs)asm.CreateInstance(t.FullName,true);
ts.DoIt();
var sm1
= from c in t.GetCustomAttributes(typeof(XylAttribute),false) select c;
foreach (XylAttribute x in sm1)
{
Console.WriteLine(x.Msg);
}

}
}

 

这里 我们同样要引入XylF的程序集,然后是用assembly.load的方法来晚期绑定程序集,然后使用linq 返回类型属于Class实现了Cs接口的类的枚举,然后进行迭代创建实体然后穿换成接口 调用接口的方法。

我们出入了插件的名字,就调用了插件的方法。 就说到了这里吧 发烧ing`````吃药

 

转载请注明出处:www.cnblogs.com/xylasp

欢迎加关注 呵呵