之前一直想學學外掛程式編程, 主要的原因是感到現在的客戶需求變化不定 ,如果把全部功能整合在一個執行檔案中的話,修改,升級起來很不方便, 所以想採用外掛程式編程的方式, 只需要構建好了程式架構之後, 每完成一個功能,就可以讓使用者審核一個, 化整為零,讓Team Dev和客戶都能構掌握項目開發的進度. 同時大家通過這種方式,增強對項目按時完成的信心.
以下資料主要是從haha blog中獲得的, 從網上找了很多類似的資料,只有這個我覺得是比較適合初學者
//1 定義外掛程式介面,將其編譯成 dll,例如:
using System;
namespace PluginInterface
...{
public interface IShow
...{
string Show() ;
}
}
//2 編寫外掛程式. 建立dll工程,並引用第一步做的dll外掛程式,實現其介面,例如:
namespace PluginA
...{
public class PluginA : PluginInterface.IShow
...{
public string Show()
...{
return "I am plugin A" ;
}
}
}
收集程式集:
//3. 在指定目錄下尋找Dll檔案
private void frmMain_Load(object sender, System.EventArgs e)
...{
//擷取Plugins目錄中所有的DLL檔案,並儲存在combo中
try
...{
string path = Application.StartupPath ;
path = System.IO.Path.Combine(path,"Plugins") ;
foreach ( string file in System.IO.Directory.GetFiles(path,"*.dll"))
...{
this.cmbPlugins.Items.Add(file) ;
}
}
catch (Exception ex)
...{
MessageBox.Show(ex.Message ) ;
}
}
使用外掛程式
private void btnExecute_Click(object sender, System.EventArgs e)
...{
try
...{
//1. 獲得 檔案名稱
string asmFile = this.cmbPlugins.Text ;
string asmName = System.IO.Path.GetFileNameWithoutExtension(asmFile) ;
if ( asmFile != string.Empty )
...{
//2. 利用反射,構造DLL檔案的執行個體
System.Reflection.Assembly asm = System.Reflection.Assembly.LoadFrom(asmFile) ;
//3. 利用反射,從程式集(DLL)中,提取類,並把此類執行個體化
PluginInterface.IShow iShow = (PluginInterface.IShow)
System.Activator.CreateInstance(asm.GetType(asmName + "Namespace." + asmName+"Class")) ;
//4. 在主程式中使用這個類的執行個體
this.label2.Text = iShow.Show();
}
}
catch ( Exception ex )
...{
MessageBox.Show(ex.Message ) ;
}
}
當然這個常式可以說是沒有實用價值, 但是非常簡單,明白.
如果要實際應用外掛程式開發的話, 一般要加入一些自訂的屬性,以及其他的一些約束.