[WinForm] C#的外掛程式開發)

來源:互聯網
上載者:User
之前一直想學學外掛程式編程, 主要的原因是感到現在的客戶需求變化不定 ,如果把全部功能整合在一個執行檔案中的話,修改,升級起來很不方便, 所以想採用外掛程式編程的方式, 只需要構建好了程式架構之後, 每完成一個功能,就可以讓使用者審核一個, 化整為零,讓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);
    }
}

常式下載:
http://www.hahasoft.cn/Blog/attachments/month_0605/62006527155316.rar

當然這個常式可以說是沒有實用價值, 但是非常簡單,明白. 

如果要實際應用外掛程式開發的話, 一般要加入一些自訂的屬性,以及其他的一些約束.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.