赞
踩
在本篇文章中,会示范如何在.NET中配合App config中的设定,来决定程序所要载入的dll及class
这种实作技巧,在plug-in中算是蛮常见的用法
首先,要宣告一个interface,就如下叫做Orz吧
并且将Orz放到一个独立的DLL项目中,并编译该DLL
- public interface Orz
- {
- int ID { get; set; }
- void Test();
- }
再来建立一个Client的EXE档项目,我是使用Console项目,并放入下面代码
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("============ Test interface Orz from config ============");
- string DllName = ConfigurationSettings.AppSettings["DllName"];
- string ClassName = ConfigurationSettings.AppSettings["ClassName"];
- try
- {
- Orz orz = Assembly.Load(DllName).CreateInstance(ClassName) as Orz;
- orz.ID = 999;
- orz.Test();
- }catch(Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
-
- Console.ReadLine();
- }
- }
App.config
- <?xml version="1.0" encoding="utf-8" ?>
- <configuration>
- <appSettings>
-
- <!-- you can test config 1 or 2 to test runtime change dll -->
-
- <!-- config 1-->
- <!-- modify MyImplement.XD2 to test -->
- <add key="DllName" value="MyImplement" />
- <add key="ClassName" value="MyImplement.XD2" />
-
- <!-- config 2-->
- <!-- modify MyImplement2.Ghost to test -->
- <!--
- <add key="DllName" value="MyImplement2" />
- <add key="ClassName" value="MyImplement2.Ghost" />
- -->
- </appSettings>
- </configuration>
此时若执行起来,会出现
因为我在项目中并没有加上任何实作的参考.......
接下来加上两个dll项目,并且实践MyInterface中的Orz介面
- public abstract class XD : Orz
- {
- protected int id;
-
- #region Orz Members
-
- public virtual void Test()
- {
- Console.WriteLine("Do XD.Test(), ID[" + id + "]");
- }
-
- #endregion
-
- #region Orz Members
-
- int Orz.ID
- {
- get
- {
- return id;
- }
- set
- {
- id = value;
- }
- }
-
- #endregion
-
- }
- public class Ghost : Orz
- {
- protected int id;
- protected string name;
-
- public Ghost()
- {
- name = "ghost";
- }
- #region Orz Members
-
- public int ID
- {
- get
- {
- return id;
- }
- set
- {
- id = value + 100;
- }
- }
-
- public virtual void Test()
- {
- Console.WriteLine("Do Ghost.Test(), ID[" + id + "], Name[" + name + "]");
- }
-
- #endregion
- }
然后编译整个项目,接下来将dll及exe及app.config复制到同一个文件夹中
接下来就可以修改app.config中的设定
plug-in不同的dll来执行了
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。