盾怪网教程:是一个免费提供流行杀毒软件教程、在线学习分享的学习平台!

用 .NET 完成插件机制

时间:2024/12/23作者:未知来源:盾怪网教程人气:

[摘要]在.NET中,一个完整的类型名称的格式如 "类型名, 程序集名"。例如:"System.Configuration.NameValueSectionHandler, S...
 

在.NET中,一个完整的类型名称的格式如 "类型名, 程序集名"。

例如:"System.Configuration.NameValueSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"。

  • 类型名为:System.Configuration.NameValueSectionHandler,这是带名字空间的完整类型名。
    你也可以使用该类型的FullName得到。
    如:string typeName = typeof(NameValueSectionHandler).FullName;
  • 程序集名为:"System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
    程序集名为System,系统为自动为其适配扩展名(如System.dll或System.exe);
    Version、Culture、PublicKeyToken为程序集的具体版本、文化背景、签名,没有特定要求,这些都可以省略。

我们可以根据类型的名称,来动态载入一个所需要的类型。如:

string typeName = "System.Configuration.NameValueSectionHandler, System";
Type t = Type.GetType(typeName);
Object obj = Activator.CreateInstance(t);

System.Configuration.NameValueSectionHandler obj = (System.Configuration.NameValueSectionHandler)Activator.CreateInstance(t);

此时,obj 就是所需要的类型实例。

通常的插件,是需要实现一定的接口的类。因此,在载入插件之前,需要确定该插件类型是否是合适的。
比如,一个插件的接口为 IPlugin,那么我们可以用如下方式来识别:

string interfaceName = typeof(IPlugin).FullName;
string typeName = "Muf.MyPlugin, MyPlugin";
Type t = Type.GetType(typeName);
             
if (  t == null
 

关键词:用 .NET 完成插件机制




Copyright © 2012-2018 盾怪网教程(http://www.dunguai.com) .All Rights Reserved 网站地图 友情链接

免责声明:本站资源均来自互联网收集 如有侵犯到您利益的地方请及时联系管理删除,敬请见谅!

QQ:1006262270   邮箱:kfyvi376850063@126.com   手机版